我有一个Show_for的Form_for。我想在form_for中使用fields_for来添加band。事情是,在使用表单更新记录时,我不希望字段绑定到频段。如果乐队名称发生变化,我想用新乐队更新演奏。
节目通过表演加入乐队
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记录 - 我希望它能做一个Band.find_or_create并用新乐队的id更新性能记录。这样,用户可以通过删除名称并添加其他乐队名称来替换节目中的乐队。
渲染的html应该包含性能ID而不是band id(我认为)
类似的东西:
<input id="show_performance_attributes_1_id" name="show[performance_attributes][1][id]" type="hidden" value="62">
这是怎么做到的?
答案 0 :(得分:0)
好的,所以我能够找到自己问题的解决方案。我可能没有在原始问题中提供足够的细节。
但解决方案只是将性能模型用作Fields_for
中的嵌套字段而不是band模型。将展示模型更改为accepts_nested_attributes_for performances
并将效果模型更改为accepts_nested_attributes_for band