开发者

Rails 3 Automatically Making Joined Table Associations

I'm having trouble figuring out how to create new entries in a table and automatically create the associated relationship in the joined table.

Here are my models:

class Building < ActiveRecord::Base
  has_many :user_buildings
  has_many :users, :through => :user_buildings
end

class User < ActiveRecord::Base
  has_many :user_buildings
  has_many :buildings, :through => :user_buildings
  ....
end

class UserBuilding < ActiveRecord::Base
  belongs_to :user
  belongs_to :building
end

Now my user model is also used for devise so I've been using the current_user helper.

To retrieve all the buildings i use

current_user.buildings

So from there I thought I could use

current_user.buildings.build

to create a new building associated with the user and update the joined table; however, this only a开发者_开发技巧dds the building to the buildings table and doesn't make the association in the user_buildings table.

I have been reading the documentation at http://api.rubyonrails.org/classes/ActiveRecord/Associations/ClassMethods.html, but I can't seem to figure out the direction I need to go.

Thanks!


You need to update the collection of buildings on current user and rails will handle updating the join table for you.

current_user.buildings << Building.new(:some_building_attributes => :some_value)
current_user.save
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜