【问题标题】:accepts_nested_attributes_for through join table with attributes on the join通过连接表接受_nested_attributes_for 与连接上的属性
【发布时间】:2011-04-15 08:17:18
【问题描述】:

如何在 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

团队有_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

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

【问题讨论】:

标签: ruby-on-rails activerecord


【解决方案1】:
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'}]}])

我没有检查过创建,所以数组和散列可能有点乱,但你明白了。您需要 Team 和 Interaction 模型上的accepts_nested_attributes。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-05-02
    • 1970-01-01
    • 2021-05-17
    • 2019-08-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多