Carrierwave saves object data to the database instead of the file name

Hi I just can't find out what is wrong with my code. I have two models: Elements and images and the relationship between them

 class Item < ActiveRecord::Base
  attr_accessible :category_id, :user_id, :title, :description, :published, :start_date, :end_date, :images_attributes
  has_many  :images, :dependent => :destroy
  accepts_nested_attributes_for :images, :reject_if => :all_blank, :allow_destroy => true
  mount_uploader :name, ImageUploader 
end

class Image < ActiveRecord::Base
  belongs_to :item
  mount_uploader :image, ImageUploader  
  attr_accessible :item_id, :name  
end

I call 3 Carrierwave instances in items_controller.rb to add 3 images to the created item

def new
    @item = Item.new
    3.times { @item.images.build }
  end

The presentation form is as follows:

<%= f.fields_for :images  do |builder| %>
   <p> <%= builder.text_field :name  %> </p>
 <% end %>

Which returns to this lost code:  <input id="item_images_attributes_0_name" name="item[images_attributes][0][name]" type="file">

When adding and saving a new element, I get the object data instead of the file name (suit.jpg) in my database:

--- !ruby/object:ActionDispatch::Http::UploadedFile 
content_type: image/jpeg
headers: |
  Content-Disposition: form-data; name="item[images_attributes][0][name]"; filename="suit.jpg"
  Content-Type: image/jpeg

original_filename: suit.jpg
tempfile: !ru

Screenshot from the database table below:

https://lh3.googleusercontent.com/_USg4QWvHRS0/TXDT0Fn-NuI/AAAAAAAAAHL8/91Qgyp5jK3Q/carrierwave-objest-database-saved.jpg

Does anyone have any ideas how to solve them?

+3
2

, (), filename ( ImageUploader) .

def filename
  @name ||= "foo"
end
+1

, : image, db .

1: , ( " , ".)

rails g migration add_image_to_images image:string
rake db:migrate

2: attr_accessible, .

class Image < ActiveRecord::Base
  belongs_to :item
  mount_uploader :image, ImageUploader  
  attr_accessible :item_id, :name, :image  
end

3:

<%= f.fields_for :images  do |builder| %>
  <p> 
    <%= builder.text_field :name  %>
    <%= builder.file_field :image  %> 
  </p>      
<% end %>

4: Item.

class Item < ActiveRecord::Base
  attr_accessible :category_id, :user_id, :title, :description, :published, :start_date, :end_date, :images_attributes
  has_many  :images, :dependent => :destroy
  accepts_nested_attributes_for :images, :reject_if => :all_blank, :allow_destroy => true
end

: , .

, , , , , , , .

, .

+1

Source: https://habr.com/ru/post/1796297/


All Articles