使用回形针的嵌套表格
问题描述:
我有一个称为posts的模型,它有很多附件。使用回形针的嵌套表格
附件模型使用回形针。
我为创建附件它工作得很好,一个独立的模型,这是因为这里指示视图(https://github.com/thoughtbot/paperclip):
<% form_for :attachment, @attachment, :url => @attachment, :html => { :multipart => true } do |form| %>
<%= form.file_field :pclip %>
<%= form.submit %>
<% end %>
在帖子中嵌套表格看起来像这样:
<% @attachment = @posts.attachments.build %>
<%= form_for(@posts) do |f| %>
<% if @posts.errors.any? %>
<div id="error_explanation">
<h2><%= pluralize(@posts.errors.count, "error") %> prohibited this post from being saved:</h2>
<ul>
<% @posts.errors.full_messages.each do |msg| %>
<li><%= msg %></li>
<% end %>
</ul>
</div>
<% end %>
<div class="field">
<%= f.label :name %><br />
<%= f.text_field :name %>
</div>
<div class="field">
<%= f.label :description %><br />
<%= f.text_area :description %>
</div>
<div class="field">
<%= f.fields_for :attachments, @attachment, :url => @attachment, :html => { :multipart => true } do |at_form| %>
<%= at_form.file_field :pclip %>
<% end %>
</div>
<div class="actions">
<%= f.submit %>
</div>
<% end %>
附件记录被创建,但它是空的。该文件未上传。与此同时,该职位已成功创建...
任何想法?
答
你缺少的:多选择在您的表单定义:
<% @attachment = @post.attachments.build %>
<%= form_for @post, :html => { :multipart => true } do |f| %>
<% if @post.errors.any? %>
<div id="error_explanation">
<h2><%= pluralize(@post.errors.count, "error") %> prohibited this post from being saved:</h2>
<ul>
<% @post.errors.full_messages.each do |msg| %>
<li><%= msg %></li>
<% end %>
</ul>
</div>
<% end %>
<div class="field">
<%= f.label :name %><br />
<%= f.text_field :name %>
</div>
<div class="field">
<%= f.label :description %><br />
<%= f.text_area :description %>
</div>
<div class="field">
<%= f.fields_for :attachments, @attachment do |at_form| %>
<%= at_form.file_field :pclip %>
<% end %>
</div>
<div class="actions">
<%= f.submit %>
</div>
<% end %>
此外,您@posts变量确实应该@Post(单实例的ActiveRecord,而不是ActiveRecord的实例的数组)。
+1 此外,我不认为你需要它'fields_for'块。 – Preacher 2011-05-01 21:14:44
好,我错过了那一个。我更新了代码片段。还删除了:url选项(位于fields_for级别),该选项不属于那里。 – mbreining 2011-05-01 22:01:38
谢谢吨家伙! – Elliot 2011-05-02 18:08:43