How to seed the path to an image?

£可爱£侵袭症+ 提交于 2019-12-23 10:14:43

问题


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.

回答1:


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



回答2:


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



来源:https://stackoverflow.com/questions/32522992/how-to-seed-the-path-to-an-image

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!