1

我对 Rails 中的嵌套表单非常陌生,所以我确信我可能在这里遗漏了一些东西。我正在关注一个回形针教程,其中article有很多assets(回形针附件)

我坚持的部分是使用article控制器创建多个文件上传字段。

您将在部分表单中看到我在底部附近添加了资产模型:

<%= form_for(@article) do |f| %>
  <% if @article.errors.any? %>
    <div id="error_explanation">
      <h2><%= pluralize(@article.errors.count, "error") %> prohibited this article from being saved:</h2>

      <ul>
      <% @article.errors.full_messages.each do |msg| %>
        <li><%= msg %></li>
      <% end %>
      </ul>
    </div>
  <% end %>

  <div class="field">
    <%= f.label :title %><br>
    <%= f.text_field :title %>
  </div>
  <div class="field">
    <%= f.label :content %><br>
    <%= f.text_area :content %>
  </div>

  <%= f.fields_for :asset do |asset| %>
    <%= asset.file_field :image %>
  <% end %>

  <div class="actions">
    <%= f.submit %>
<% end %>

在文章控制器中,我添加了我认为会构建表单的该部分的内容 5 次:

  def new
    @article = Article.new
    5.times {@article.assets.build}
  end

为了更好地衡量,这里是文章和资产模型:

文章

class Article < ActiveRecord::Base
    has_many :assets
end

资产

class Asset < ActiveRecord::Base
    belongs_to :article

    has_attached_file :image, 
        :style => {
            :thumb => '150x150#',
            :medium => '300x300>',
            :large => '600x600>'
        } 
end

我错过了什么?

4

2 回答 2

2

为了获取:assets生成的多个字段,您需要accepts_nested_attributes_for :assetsArticle模型中添加。

# article.rb
class Article < ActiveRecord::Base
    has_many :assets
    accepts_nested_attributes_for :assets
end

那么在你看来:

<%= f.fields_for :assets do |asset| %>
  <%= asset.file_field :image %>
<% end %>
于 2013-08-22T22:47:32.457 回答
1

我认为您需要将嵌套字段指定为复数(与关联相同):

<%= f.fields_for :assets do |asset| %>
  <%= asset.file_field :image %>
<% end %>
于 2013-08-22T22:28:48.980 回答