The application has a product :

class Product < ActiveRecord::Base has_many :photos, dependent: :destroy validates :title, :content, presence: true validates_length_of :photos, maximum: 5 end 

Photos to them are made as invested resources. photo.rb:

 class Photo < ActiveRecord::Base belongs_to :product mount_uploader :image, ImageUploader end 

Trying to import products from csv:

 CSV.foreach(file.path, headers: true, header_converters: :symbol,col_sep: '||') do |row| Product.create!( :title=> row[1], :content=> row[2], :photos_attributes => { row[3].each do |img| :image => img end } ) end 

Error: ... / app / models / product.rb: 322: syntax error, unexpected =>, expecting keyword_end: image => img ^ ... / app / models / product.rb: 323: syntax error, unexpected ' \ n ', expecting =>

Example csv:

 title||content||img name Товар 1 || Описание товра 1 || "[""img_1.jpg"", ""img_4.jpg"", ""img_5.jpg""]" Товар 2 || Описание товра 2 || "[""img_1.jpg"", ""img_2.jpg"", ""img_3.jpg""]" Товар 3 || Описание товра 3 || "[""img_1.jpg"", ""img_5.jpg""]" Товар 4 || Описание товра 4 || [] 

When importing images, there are 2 problems: - how to create several photos at once - how to upload a file to rails correctly?

  • Well, you need to open the file IO.read and send it as image - Mal Skrylev
  • And what kind of model Advert? - cheops
  • @cheops sorry. corrected - alexin
  • @ Mal'Skrylev, how can I do a brute force there? because photos in csv as hash inserted. - alexin
  • @alexin like what? show in the post - Mal Skrylev

1 answer 1

In the photo attributes, you need to specify not just the file name, but directly upload it:

 photos_attributes: row[3].map { |img| { image: IO.read(img) } } 

There is also an option to use the rack boot class :

 Rack::Test::UploadedFile.new("me.jpg", "image/jpeg") 
  • thanks for the advice. but with such a record, the error syntax error, unexpected ':', expecting '}' ...utes: row[3].map { |img| image: IO.read(img) } ... ^ syntax error, unexpected ':', expecting '}' ...utes: row[3].map { |img| image: IO.read(img) } ... ^ . tried to rewrite in the form :photos_attributes => { row[3].map { |img| image: IO.read(img) } } :photos_attributes => { row[3].map { |img| image: IO.read(img) } } , but in this case also the error: .../app/models/advert.rb:323: syntax error, unexpected ':', expecting '}' row[3].map { |img| image: IO.read(img) } ^ .../app/models/advert.rb:323: syntax error, unexpected '\n', expecting => .../app/models/advert.rb:323: syntax error, unexpected ':', expecting '}' row[3].map { |img| image: IO.read(img) } ^ .../app/models/advert.rb:323: syntax error, unexpected '\n', expecting => - alexin
  • one
    working) beat the brow, boyar! - alexin 8:49 pm
  • bad yesterday checked. when loading the csv error No implicit conversion of Symbol into Integer . The problem is in downloading photos. if this line is removed everything is created correctly. - alexin
  • @alexin updated - Mal Skrylev