0

我有一个Form_for的显示模型。我想在form_for中使用fields_for来添加乐队。问题是我不想在使用表单更新记录时将字段绑定到乐队。如果乐队名称发生变化,我想用新乐队更新演奏。使用嵌套形式的联接模型(has_many:通过关系)

节目都是通过演出加入了与乐队

class Show < ActiveRecord::Base 
    has_many :performances 
    has_many :bands, through: :performances 
    accepts_nested_attributes_for :bands 
end 

class Band < ActiveRecord::Base 
    attr_accessible :name, :website, :country, :state 
    has_many :performances 
    has_many :shows, through: :performances 

    validates :name, presence: true, uniqueness: true 
end 

class Performance < ActiveRecord::Base 
    attr_accessible :show, :band 
    belongs_to :show 
    belongs_to :band 
end 

这里是我的形式。 (简体)

<%= form_for @show do |f| %> 
    #fields 
    <%= f.fields_for :bands do |b| %> 
     <%= b.text_field :name %>  
    <% end %> 
<%end> 

问题是如果这是用来更改乐队名称,它会更改乐队名称(疯狂的权利?)。我不希望它更新乐队记录 - 我希望它执行Band.find_or_create并使用新乐队的ID更新演奏记录。这样,用户可以通过删除名称并添加另一个乐队名称来替换演出中的乐队。

呈现的HTML应包括性能标识不带ID(我认为)

喜欢的东西:

<input id="show_performance_attributes_1_id" name="show[performance_attributes][1][id]" type="hidden" value="62"> 

这是如何完成的?

+1

您必须在处理发布请求的操作中编写一些代码。 – phoet

+0

你确定我不需要改变我打电话给fields_for的方式吗? – wiredin

回答

0

好吧,所以我找到了解决我自己的问题。我原来的问题可能没有提供足够的细节。

但是,解决方案只是将性能模型用作Fields_for中的嵌套字段,而不是带模型。将展示模型更改为accepts_nested_attributes_for performances并将性能模型更改为accepts_nested_attributes_for band

相关问题