accepted_nested_attributes_for通过连接表与连接上的属性

时间:2010-09-21 17:41:42

标签: ruby-on-rails activerecord

如何在连接表中添加属性时,在has_many:through关联中使用ActiveRecord的accepts_nested_attributes_for助手?

例如,假设我有一个团队模型:

class Team < ActiveRecord::Base
  role = Role.find_by_name('player')
  has_many  :players,
            :through    => :interactions, 
            :source     => :user, 
            :conditions => ["interactions.role_id = ?", role.id] do
              class_eval do
                define_method("<<") do |r|                                                             
                  Interaction.send(:with_scope, :create => {:role_id => role.id}) { self.concat r }
                end
              end
            end
end

团队has_many playersinteractions,因为用户可以占据多个角色(玩家,经理等)。

如何在连接表中添加属性的同时使用accepts_nested_attributes_for?

如果我有现有的团队记录team和现有的用户记录user,我可以这样做:

team.players << user
team.players.size 
=> 1

但是如果我用嵌套播放器创建一个新团队:

team = Team.create(:name => "New York Lions", 
                   :players_attributes => [{:name => 'John Doe'}])
team.players.size
=> 0

在最后一个示例中,创建了团队,用户和交互记录(团队确实让用户通过交互),但此处未设置interact.role_id属性。

1 个答案:

答案 0 :(得分:2)

class Team < ActiveRecord::Base
  accepts_nested_attributes_for :interactions

class Interaction < ActiveRecord::Base
  accepts_nested_attributes_for :players


team = Team.create(:name => "New York Lions", :interactions_attribues => [{
                   :players_attributes => [{:name => 'John Doe'}]}])

我没有检查过创建,所以可能有阵列和哈希有点乱,但你明白了。您需要团队中的accepts_nested_attribute和交互模型。