【问题标题】:How to seed the path to an image?如何播种图像的路径?
【发布时间】:2015-09-11 11:58:21
【问题描述】:

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,可以确认它是 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 method create!'对于 nil:NilClass`。
  • @organization.image.create 不适用于一对一关系

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


【解决方案1】:

因为您的错误清楚地说明了问题所在。原来@organization 还没有任何图像。所以试试

file  = File.open(File.join(Rails.root,'app/assets/other/image.jpg'))
image = @organization.build_image(filename: file)
image.save

【讨论】:

  • 谢谢@GB。我试过了,但它在播种错误时生成:CarrierWave::FormNotMultipart: You tried to assign a String or a Pathname to an uploader, for security reasons, this is not allowed..
【解决方案2】:

您正在定义组织和图像之间的一对一关系,创建操作将不起作用,您有两种方法可以做到这一点

1. 将关联更改为一对多以使您的代码正常工作

2. 另一个是这样做的:

@image = Image.create(#your code)
@image.organization = @organization

关注Link

【讨论】:

  • 谢谢!请参阅我添加到 OP 的更新,了解选项 2 为我生成的错误消息。
猜你喜欢
  • 2019-05-23
  • 1970-01-01
  • 2016-09-20
  • 1970-01-01
  • 2018-04-25
  • 1970-01-01
  • 1970-01-01
  • 2013-09-07
相关资源
最近更新 更多