开发者

has_many through build

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


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
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜