如何播种图像的路径?

时间:2015-09-11 11:58:22

标签: ruby-on-rails ruby ruby-on-rails-4 asset-pipeline

OrganizationImage有一个1-to-1 relationshipImage有一个名为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.

2 个答案:

答案 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