5

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

Wahtever
  • 3,597
  • 10
  • 44
  • 79

1 Answers1

4

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.

Wahtever
  • 3,597
  • 10
  • 44
  • 79
  • 1
    Maaan!!! That's what I was looking for the whole day yestarday!! Thank you!! You've made my day! – aprok Sep 25 '13 at 09:24
  • I have a question to you. I have in my _form.html.erb <%= f.link_to_add "Add image", :poster_images %>. And each time,when I'm trying to edit my poster, I have so many links to add image as I have images in my existing poster. Any ideas how to fix it? – aprok Sep 25 '13 at 09:49
  • @ArseniiProhorchik - try moving the `link_to_add` outside the `fields_for` block but still inside the main form. – Wahtever Sep 25 '13 at 18:09
  • It is there.. still seeing it by default while editing poster. – aprok Sep 26 '13 at 10:49