has_many through build

自古美人都是妖i 提交于 2019-12-10 17:53:36

问题


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.


回答1:


Try saving the user object instead.

acc = usr.accounts.build
usr.save



回答2:


You'll get a full error report if you use .save! rather than .save

Using a has_many :through please try adding a model

class Manage < ActiveRecord::Base
  belongs_to :user
  belongs_to :account
end


来源:https://stackoverflow.com/questions/7036870/has-many-through-build

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!