如何播种图像路径? [英] How to seed the path to an image?
问题描述
Organization
和Image
具有1-to-1 relationship
. Image
有一个称为filename
的列,该列存储文件的路径.我在资产管道中包含这样的文件:app/assets/other/image.jpg
.播种时如何包含此文件的路径?
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?
我在种子文件中尝试过
@organization = ...
@organization.image.create!(filename: File.open('app/assets/other/image.jpg'))
# I also tried:
# @organization.image.create!(filename: 'app/assets/other/image.jpg')
两者都会产生错误:
NoMethodError: undefined method `create!' for nil:NilClass
我检查了debugger
并可以确认不是 @organization
是零.
如何进行这项工作并将文件的路径添加到Image
模型?
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')
我也尝试过:
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.
推荐答案
由于您的错误清楚地说明了问题所在.事实证明@organization
还没有任何图像.所以尝试
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
这篇关于如何播种图像路径?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!