Reputation: 43636
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?
Upvotes: 10
Views: 5369
Reputation: 418
A smart way to put the content in seed file like this
Rails.root.join("#{Rails.root}/app/assets/images/image_a.jpg")
Upvotes: 0
Reputation: 2763
This is what I do on my case:
["Sublime Text 3", "Internet Explorer"].each do |title|
unless Post.exists?(title: title)
post = Post.create!(title: title,
subtitle: "Subtitle of the #{title}",
content: "A sample post of the content about #{title}",
author: User.first)
post.attachments_attributes = [file: Rails.root.join("spec/fixtures/photo.jpg").open]
post.save!
end
end
Upvotes: 0
Reputation: 6072
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.
Upvotes: 19