我有文章,有很多ArticleAssets。相当简单。在文章的编辑表单上,我只想添加新的文章资产。我不需要编辑当前的部分,所以我创建了一个像这样的部分:
<% f.fields_for :article_assets, article_asset do |builder| -%>
<div class="article_asset">
<%= builder.file_field :image %>
<%= builder.check_box :is_flagged, :class => "isFlagged" %> isFlagged
</div>
<% end -%>
没有集合,因为我一次只需要一个对象而不需要现有文章资产中的数据。以edit.erb的形式,我呈现以下内容:
<%= render :partial => 'article_asset', :locals => {:f => f}, :object => ArticleAsset.new %>
这使得一篇新文章资产显示我可以添加信息,到目前为止一切都很酷。重要的是,此字段获取文章[article_assets_attributes] [0] [is_flagged] 的名称形式。一切都很好,因为这也将隐藏字段组合在一起,其中一个复选框在rails中与其余字段一起出现。然后我有一个“添加项目”链接来执行此操作:
page.insert_html :bottom, :article_assets_fields, :partial => "article_asset", :locals => {:f => f}, :object => ArticleAsset.new
点击此链接会根据需要在所创建的字段下方提供一个新字段,其中包含文章[article_assets_attributes] [1] [is_flagged] 的复选框字段的名称格式。增量,这是完美的!然而,添加另一个具有相同链接,也提供相同的形式(也是标识符1,重复),这使得提交表单只有2项而不是3.有谁知道为什么会发生这种情况,我可以做什么解决它?
Ruby on Rails 2.3.11
答案 0 :(得分:0)
嵌套表格2.3失败。这一次是我存在的一段时间的祸根,甚至看过轨道播报等。这是我的如何:
1)这可以在article.rb
中找到 after_update :save_article_assets
def new_article_asset_attributes=(article_asset_attributes)
article_asset_attributes.each do |attributes|
article_assets.build(attributes)
end
end
def existing_article_asset_attributes=(article_asset_attributes)
article_assets.reject(&:new_record?).each do |article_asset|
attributes = article_asset_attributes[article_asset.id.to_s]
if attributes
article_asset.attributes = attributes
else
article_assets.delete(article_asset)
end
end
end
def save_article_assets
article_assets.each do |article_asset|
article_asset.save(false)
end
end
2)在某个地方帮忙:
def add_article_asset_link(name)
button_to_function name, :class => "new_green_btn" do |page|
page.insert_html :bottom, :article_assets, :partial => "article_asset", :object => ArticleAsset.new()
end
end
def fields_for_article_asset(article_asset, &block)
prefix = article_asset.new_record? ? 'new' : 'existing'
fields_for("article[#{prefix}_article_asset_attributes][]", article_asset, &block)
end
3)在你的部分:
<% fields_for_article_asset(article_asset) do |aa| %>
<tr class="article_asset">
<td><%= aa.text_field :foo %></td>
<td><%= link_to_function "remove", "$(this).up('.article_asset').remove()" %></td>
</tr>
<% end %>
4)在_form:
<table>
<%= render :partial => "article_asset", :collection => @article.article_assets %>
</table>
<%= add_article_asset_link "Add asset" %>