Rails: import of photos from csv



  • The annex is product:

    class Product < ActiveRecord::Base
      has_many :photos, dependent: :destroy
    

    validates :title, :content, presence: true
    validates_length_of :photos, maximum: 5
    end

    The photos are made as resources. photo.rb:

    class Photo < ActiveRecord::Base
    belongs_to :product

    mount_uploader :image, ImageUploader
    end

    I'm trying to import csv products:

    CSV.foreach(file.path, headers: true, header_converters: :symbol,col_sep: '||') do |row|
    Product.create!(
    :title=> row[1],
    :content=> row[2],

    :photos_attributes =&gt; {
      row[3].each do |img|
        :image =&gt; img
      end
     }
    

    )
    end

    Mistake:
    ♪ ♪ ./app/models/product.rb:322: syntax error, unexpected = constant, expecting keyword_end :image = wealth img ^
    ♪ ♪ ./app/models/product.rb:323: syntax error, unexpected '\n', expecting=state

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

    In importing pictures, two problems arise:

    • how to start a few photos.
    • how is it right to download the file rails?



  • Attribut photos need to be shown not just the name of the file, but directly download the blank:

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

    there is also an option http://www.rubydoc.info/github/brynary/rack-test/Rack/Test/UploadedFile so:

    Rack::Test::UploadedFile.new("me.jpg", "image/jpeg")
    



Suggested Topics

  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2