使用Paperclip的Rails忽略空附件

时间:2013-09-12 12:34:38

标签: paperclip ruby-on-rails-4

我正在使用带有导轨的回形针并且它工作正常,但是我的问题是在更新时如果我不重新选择图像,那么它将记录保存为零。这是我的代码:

<div class="form-group">
  <div class="media">
    <%= image_tag program_avatar(b), :id => 'avatar', :class => 'thumbnail media-object pull-left', :height => 100, :width => 100 %>
    <div class="media-body padding-top-40">
      <%= b.file_field :avatar, :class => 'file-upload' %>
    </div>
  </div>
</div>

<div class="form-group">
  <div class="media">
    <%= image_tag program_banner(b), :class => 'thumbnail media-object pull-left', :height => 100, :width => 300 %>
    <div class="media-body padding-top-40">
      <%= b.file_field :banner, :class => 'file-upload' %>
    </div>
  </div>
</div>

和控制器:

respond_to do |format|
  if @program.update(program_params)
    format.html { redirect_to(program_path(@program), :notice => "Program updated") }
    format.js { render :json => @program.json }
  else
    format.html { render :new, :notice => "Error please try again" }
    format.js { render :json => "Error please try again" }
  end
end

模特:

图书模型

has_one :book_content, :dependent => :destroy  
accepts_nested_attributes_for :book_content, :allow_destroy => true

Book_content模型:

has_attached_file :avatar, :styles => { :medium => "300x300>", :thumb => "100x100>" }, :default_url => "/images/:style/missing.png"
has_attached_file :banner, :styles => { :header => "600x150", :setting => "300x100"  }, :default_url => "/images/:style/found.jpeg"
belongs_to :book

这是一个嵌套表单,但因为它有多个附件所以我无法使用reject_if

如果没有选择文件,如何告诉paperclip保留原始文件?

谢谢

1 个答案:

答案 0 :(得分:4)

经过一番研究后,我发现我的问题并没有通过参数中的id,所以我有这个:

params.require(:book).permit(:book_name, book_content_attributes: [:media, :rating, :book_id])

将其更改为:

params.require(:book).permit(:book_name, book_content_attributes: [:id, :media, :rating, :book_id])

注意添加的:id,现在它可以正常工作。