Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CarrierWave::FormNotMultipart error when creating records using seed.rb file

I have a model that has a image column. I am using CarrierWave to upload images (I am following this rails cast to do this.

Now, I want to create some default records using seed.rb file but I have failed to provided correct parh/url to the images.

So, I have images in List item app/public/images/ folder and this is the code from the seed.rb file:

gems = {

    test1: {

        name: 'test1',
        description: 'test1',
        image: '/public/images/test1.png',
    },

    test2: {

        name: 'test2',
        description: 'test2',
        image: '/public/images/test2.png'
}

gems.each do |user, data|

  gem = DemoGem.new(data)

  unless DemoGem.where(name: gem.name).exists?
    gem.save!
  end
end

And I am getting the following error when I run rake db:seed command:

CarrierWave::FormNotMultipart: You tried to assign a String or a Pathname to an uploader, for security reasons, this is not allowed.

Could anyone tell how to provided correct url to the images?

like image 883
gotqn Avatar asked Jul 05 '14 09:07

gotqn


1 Answers

Presuming that your Gem model has the image field as a Carrierwave uploader (that is, you've got mount_uploader :image, ImageUploader or similar in your Gem model), you can assign a ruby File object to your image attribute, not a string. Something like this:

gem = Demogem.new(data)
image_src = File.join(Rails.root, "/public/images/test2.png")
src_file = File.new(image_src)
gem.image = src_file
gem.save

In your overall code, you could either change your seed data (so your image property in your hash was set to File.new(File.join(Rails.root, "/public/images/test1.jpg")) or change the way you construct your new records so it doesn't use the image by default:

gems.each do |user, data|
    gem = DemoGem.new(data.reject { |k, v| k == "image" })
    gem.image = new File(File.join(Rails.root, data["image"]))

    unless DemoGem.where(name: gem.name).exists?
        gem.save!
    end
end

The CarrierWave wiki has some documentation on this, but it's not very extensive.

like image 132
Alex P Avatar answered Sep 30 '22 22:09

Alex P