Question

I have Item Model

class Item < ActiveRecord::Base
  has_many :images, dependent: :destroy
  accepts_nested_attributes_for :images, :allow_destroy => true
end

and Image Model

class Image < ActiveRecord::Base
  belongs_to :item
  has_attached_file :picture, :styles => {:medium => "600x600>", :thumb => "100x100>"},       :default_url => "/images/:style/missing.png"
end

And in the controller, the strong parameters go

def item_params
  params.require(:item).permit(:name, :description, :price, images_attributes: [:picture, :_destroy])
end

just as the Cocoon READM says. So the basic idea is that an Item has several Images, which in turn have this paperclip field picture. Then the form is being rendered with Coccon

#views/admin/items/new.html.erb
<div class="field">
  <div class="ui teal label">Imagen</div>
  <%= f.fields_for :images do |image| %>
    <%= render partial: 'image_fields', :f => image  %>
  <% end %>
</div>

#views/admin/items/_image_fields.html.erb
<div class="nested-fields">
  <%= f.file_field :image, :class => "add-image-field" %>
  <%= link_to_remove_association "Eliminar", f, :class => "ui red mini button" %>
</div>

In the view everything seems to work fine, but then looking at the parameters sent to the controller, something is wrong:

Parameters: {"utf8"=>"✓",
"authenticity_token"=>"AIogvRQuKNrAAOjM7YsnVQx7j2MwZ1VC3LiZy0cDDrU=", 
"item"=>{
  "name"=>"", 
  "description"=>"", 
  "price"=>"12345", 
  "images_attributes"=>{
    "1394577880921"=>{
      "image"=>#<ActionDispatch::Http::UploadedFile:0x00000003182718 @tempfile=#<Tempfile:/tmp/RackMultipart20140311-27326-19i0obp>, @original_filename="blue-diamond-rings.jpg", @content_type="image/jpeg", @headers="Content-Disposition: form-data; name=\"item[images_attributes][1394577880921][image]\"; filename=\"blue-diamond-rings.jpg\"\r\nContent-Type: image/jpeg\r\n">, "_destroy"=>"false"}}}, 
 "commit"=>"Crear"}

What's that weird signature after images_attributes? It's ruining the Item saving process.

Thanks for any pointer!

Was it helpful?

Solution

You call the file_field image and it should be picture.

The rest is fine.

What is "weird" inside image_attributes:

  • "1394577880921": a temporary id, which will be replaced with a real id when the item is saved to the database. This is how rails handles nested attributes. When parsing the posted params, rails will convert this to an array of Images.
  • the value of image (which should be named picture) is the file-data, which looks weird of course
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top