Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to seed the path to an image?

Organization and Image have a 1-to-1 relationship. Image has a column called filename, which stores the path to a file. I have such a file included in the asset pipeling: app/assets/other/image.jpg. How can I include the path to this file when seeding?

I have tried in my seeds file:

@organization = ...
@organization.image.create!(filename: File.open('app/assets/other/image.jpg'))
# I also tried:
# @organization.image.create!(filename: 'app/assets/other/image.jpg')

Both generate the error:

NoMethodError: undefined method `create!' for nil:NilClass

I checked with the debugger and can confirm that it's not @organization that is nil.
How can I make this work and add the path to the file to the Image model?


Update: I tried the following:

@image = Image.create!(organization_id: @organization.id,
                       filename: 'app/assets/other/image.jpg')

And I also tried:

image = @organization.build_image(filename: 'app/assets/other/image.jpg')
image.save

Upon seeding both attempts produce the error:

CarrierWave::FormNotMultipart: You tried to assign a String or a Pathname to an uploader, for security reasons, this is not allowed.
like image 371
Marty Avatar asked Sep 11 '15 11:09

Marty


2 Answers

As your error is clearly telling what the issue is. It turns out that @organization doesn't have any image yet. So try

file  = File.open(File.join(Rails.root,'app/assets/other/image.jpg'))
image = @organization.build_image(filename: file)
image.save
like image 195
Abdul Baig Avatar answered Oct 30 '22 23:10

Abdul Baig


You are defining one to one relationship between Organization and Image, create action will not work, you have two ways to do this

1. Change association to one to many to make you code working

2. Another one is to do like this:

@image = Image.create(#your code)
@image.organization = @organization

Follow this Link

like image 3
Gaurav Gupta Avatar answered Oct 30 '22 23:10

Gaurav Gupta