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

tri*_*nia 5 activerecord ruby-on-rails

在为连接表添加属性时,如何在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
Run Code Online (Sandbox Code Playgroud)

团队已经players完成了interactions,因为用户可以占据多个角色(玩家,经理等).

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

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

team.players << user
team.players.size 
=> 1
Run Code Online (Sandbox Code Playgroud)

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

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

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

jam*_*s2m 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'}]}])
Run Code Online (Sandbox Code Playgroud)

我还没有检查创建,所以数组和哈希可能有点混乱,但你明白了。您需要团队和交互模型上的accepts_nested_attributes。