Rails为多对多的嵌套属性

问题描述:

嗨我想实现一个使用嵌套属性的功能。在创建差点的形式(针对客户)中,我想显示所有客户联赛的列表,并且在创建动作中提交表单时,我会使用@ handicap.save,这将创建差点和联赛(以及选中的联赛)。Rails为多对多的嵌套属性

我发现的唯一解决方案是不使用嵌套属性。 在新的方法中,我会从客户那里获得所有障碍并将其显示在表单中。因此,当表单在创建操作中提交时,我会进行验证..,为Customer创建@handicap记录,然后为来自表单创建关联的每个联盟ID手动创建 。

#New/Create actions in the handicaps controller 

def new 
    @leagues = @customer.leagues 
end 

def create 
    handicap = @customer.handicaps.build(handicap_params) 
    if handicap.save 
    associations = [] 
    params[:league_ids].each do |id| 
     associations << LeagueHandicap.new(handicap_id: @handicap.id, league_id: id) 
    end 
    LeagueHandicap.import(associations) 
    end 
end 

我想做handicap.save并自动创建LeagueHandicap协会。不过,我不知道如何使用嵌套属性来做到这一点。可以这样做吗?

我有以下型号:

class Customer < ActiveRecord::Base 
    has_many :handicaps, dependent: :destroy 
    has_many :leagues, dependent: :destroy 
end 

class Handicap < ActiveRecord::Base 
    belongs_to :customer 
    has_many :league_handicaps 
    has_many :leagues, through: :league_handicaps, dependent: :destroy 
end 

class LeagueHandicap < ActiveRecord::Base 
    belongs_to :handicap 
    belongs_to :league 
end 

class League < ActiveRecord::Base 
    has_many :league_handicaps 
    has_many :handicaps, through: :league_handicaps, dependent: :destroy 
end 

(许多通过LeagueHandicap盘口和联盟之间的多对多关系)

如果您允许league_ids轨应该添加它们。你需要告诉轨道它是一个数组虽然

def handicap_params 
    params.require(:handicap).permit(league_ids: []) 
end 
+0

而我该如何显示客户@联盟的形式。所以当表单是提交者时,我会得到如下所示的结果:{handicap:{info_about handicap:{},league_ids:[1,2,3]}}。我发现很难在视图中正确显示联赛。我需要使用这样的和:f.fields用于:联盟do | builder | ? –

+0

['collection_check_boxes'](http://api.rubyonrails.org/classes/ActionView/Helpers/FormOptionsHelper.html#method-i-collection_check_boxes)'f.collection_check_boxes(league_ids,League.all,:id,:名称)' –

+0

伟大的工程!但是我们不能使用相同的方法来编辑权限?如果我们使用collection_check_boxes,即使我们更改了更新方法中的检查,rails也不会删除最后一个关联并创建一个新关联。有没有办法让轨道做到这一点,所以我们不需要硬编码呢? –