Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails with Paperclip ignore empty attachments

I am using paperclip with rails and it works fine, however my problem is when updating if the i don't reselect the image, then it saves the record as nil. Here is my code:

<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>

and the controller:

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

The models:

Book model:

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

Book_content model:

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

this is a nested form, but because it has multiple attachments so i cannot use reject_if

How can tell paperclip to keep the original files if no file is selected?

Thank you

like image 289
Wahtever Avatar asked Oct 03 '22 23:10

Wahtever


1 Answers

After some research I found that my problem is not passing the id in the params, so I have this:

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

Changed it to this:

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

notice the added :id, and now it works fine.

like image 194
Wahtever Avatar answered Oct 07 '22 18:10

Wahtever