Rails file_field帮助程序不返回任何内容

时间:2012-04-16 13:50:59

标签: ruby-on-rails paperclip attachment simple-form

我正在使用简单表格。我有一个用于创建新项目的表单,以及一个用于编辑现有项目的表单。我还为每个项目都有两个文件字段。让我感到困惑的是,在创建新项目时文件字段显示正常,但在编辑现有项目时根本不会生成它们。

我在Rails 3.0中完美地工作,现在不适用于Rails 3.2.1。

表格:

<%= simple_form_for @item, :html => { :multipart => true } do |f| %>
    <%= f.input :title, :input_html => { :maxlength => 35 } %>
    <%= f.input :description, :input_html => { :maxlength => 450 } %>
    <%= f.input :secure_details, :placeholder => "Serial numbers and other stuff that will remain private", :input_html => { :maxlength => 450 } %>
    <%= f.association :bookmark, :collection => current_user.bookmarks(:order => :position), :include_blank => false %>
    <%= f.input :warranty_until, :as => :string, :input_html => { :id =>'datepicker2' } %>
    <div class="image_attachment">
        <div class="attachment_text">
            Update item photo<br />
            <small>(will replace old one)</small>
        </div>
        <div class="attachment_button">
        <% f.fields_for :assets do |asset| %>
            <%= asset.file_field :photo %>
        <% end %>
        </div>
    </div>
    <div class="image_attachment">
        <div class="attachment_text">
            Update receipt<br />
            <small>(will replace old one)</small>
        </div>
        <div class="attachment_button">
        <% f.fields_for :receipts do |receipt| %>
            <%= receipt.file_field :photo %>
        <% end %>
        </div>
    </div>
    <%= f.input :public, :label => "My friends can see this item", :input_html => { :class => "right" } %>
    <%= f.input :giveaway, :label => "Mark as giveaway", :input_html => { :class => "right" } %>
    <div class="margin_r margin_t">
        <%= f.button :submit, :class => 'small_button white right' %>
    </div>

<% end %>

基本上这部分代码不起作用:

<div class="attachment_button">
        <% f.fields_for :assets do |asset| %>
            <%= asset.file_field :photo %>
        <% end %>
</div>

生成的HTML只是空div。

同样的代码在创建新项目时有效,但在编辑现有项目时不起作用。

资产和收据均使用Paperclip存储图像。以下是Asset class的代码:

class Asset < ActiveRecord::Base
    belongs_to :item

    has_attached_file :photo, 
        :styles => {
            :thumb => "80x80#",  
            :small => "150x150>" }
    validates_attachment_size :photo, :less_than => 550.kilobytes
    validates_attachment_content_type :photo, :content_type => ['image/jpeg', 'image/png']

end

1 个答案:

答案 0 :(得分:1)

也许你忘了在你的Item模型中添加这行代码:

accepts_nested_attributes_for :receipts, :allow_destroy => true
accepts_nested_attributes_for :assets, :allow_destroy => true

并添加'=':

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

<%= f.fields_for :receipts do |receipt| %>
    <%= receipt.file_field :photo %>
<% end %>