如何播种图像的路径?
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.
由于您的错误清楚地表明问题是什么。 事实certificate@organization
还没有任何图像。 所以试试吧
file = File.open(File.join(Rails.root,'app/assets/other/image.jpg')) image = @organization.build_image(filename: file) image.save
您正在定义组织和图像之间的一对一关系,创建操作不起作用,您有两种方法可以执行此操作
1.将关联更改为一对多以使代码正常工作
另一个是这样做的:
@image = Image.create(#your code) @image.organization = @organization
请关注此链接