【发布时间】:2015-09-11 11:58:21
【问题描述】:
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,可以确认它是 not @organization 是 nil。
我怎样才能完成这项工作并将文件的路径添加到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.
【问题讨论】:
-
文件名包含路径,所以需要
@organization.image.create!(filename: 'app/assets/other/image.jpg') -
请参阅我的帖子中的
# I also tried:。这不是你的意思吗?如果我这样做,我会在播种时收到错误消息:NoMethodError: undefined method 'create!' for nil:NilClass -
使用 File.open 与直接使用路径不同,我猜路径是你真正需要的文件名属性
-
要明确一点:使用
@organization.image.create!(filename: 'app/assets/other/image.jpg')而不是@organization.image.create!(filename: File.open('app/assets/other/image.jpg'))仍然会产生错误NoMethodError: undefined methodcreate!'对于 nil:NilClass`。 -
@organization.image.create 不适用于一对一关系
标签: ruby-on-rails ruby ruby-on-rails-4 asset-pipeline