Organization
和Image
有一个1-to-1 relationship
。 Image
有一个名为filename
的列,用于存储文件的路径。我在资产管道中包含了这样一个文件:app/assets/other/image.jpg
。播种时如何包含此文件的路径?
我已尝试过种子文件:
@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
模型?
更新:我尝试了以下内容:
@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
播种后,两次尝试都会产生错误:
CarrierWave::FormNotMultipart: You tried to assign a String or a Pathname to an uploader, for security reasons, this is not allowed.
答案 0 :(得分:7)
由于您的错误清楚地表明了问题所在。事实证明@organization
还没有任何图像。所以试试
file = File.open(File.join(Rails.root,'app/assets/other/image.jpg'))
image = @organization.build_image(filename: file)
image.save
答案 1 :(得分:3)
您正在定义组织和图像之间的一对一关系,创建操作不起作用,您有两种方法可以执行此操作
1。将关联更改为一对多以使代码正常工作
2。另一个是这样做的:
@image = Image.create(#your code)
@image.organization = @organization
关注此Link