0

我有一个用于 Show 模型的 Form_for。我想在 form_for 中使用 fields_for 来添加波段。问题是我不希望在使用表单更新记录时将字段绑定到波段。如果乐队名称发生变化,我想用新乐队更新表演。

通过表演与乐队一起表演

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 而不是乐队 id(我认为)

就像是:

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

这是怎么做到的?

4

1 回答 1

0

好的,所以我能够找到自己问题的解决方案。我可能没有在原始问题中提供足够的细节。

但解决方案是简单地将性能模型用作Fields_for而不是带模型中的嵌套字段。将表演模型更改为accepts_nested_attributes_for performances并将表演模型更改为accepts_nested_attributes_for band

于 2013-11-03T18:24:15.807 回答