通过构建 has_many
我有两个型号。用户和帐户如下
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
如果我要使用rails控制台并通过以下命令创建帐户实例
acc = usr.accounts.build
acc.save
以下命令将返回创建的帐户实例
usr.accounts
但以下命令不会返回用户实例
acc.users
另外当我查看联接表时,有没有创建条目。这里缺少什么?我认为通过使用构建方法,它会自动创建连接模型条目。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
尝试保存用户对象。
Try saving the user object instead.
如果您使用 .save! 而不是 .save,您将获得完整的错误报告
使用 has_many :through 请尝试添加模型
You'll get a full error report if you use .save! rather than .save
Using a has_many :through please try adding a model