通过构建的has_many [英] has_many through build
本文介绍了通过构建的has_many的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有两个型号。用户和帐户如下:
I have two models. User and Account as follows
class Account < ActiveRecord::Base
has_many :manages
has_many :users, :through => :manages
end
class User < ActiveRecord::Base
has_many :manages
has_many :accounts, :through => :manages
end
如果我是用钢轨控制台和
If I were to use the rails console and create an instance of account by
acc = usr.accounts.build
acc.save
下面的命令将返回创建的帐户实例
The following command would return the account instance created
usr.accounts
但下面的命令不会返回用户实例
But the following command would not return the user instance
acc.users
此外,当我看着桌子加入,也没有创建条目。什么是缺少在这里?我想用它自动创建连接模型条目构建方法。
Also when I look at the Join table, there is no entry created. What am missing here? I thought by using the build method that it automatically creates the join model entry.
推荐答案
尝试节省了用户的对象,而不是
Try saving the user object instead.
acc = usr.accounts.build
usr.save
这篇关于通过构建的has_many的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文