加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

ruby – 使用seed.rb文件创建记录时出现CarrierWave :: FormNotM

发布时间:2020-12-16 21:15:58 所属栏目:百科 来源:网络整理
导读:我有一个有图像列的模型.我正在使用CarrierWave上传图像(我正在关注此 rails cast来执行此操作. 现在,我想使用seed.rb文件创建一些默认记录,但我未能为图像提供正确的parh / url. 所以,我在List item app / public / images /文件夹中有图像,这是seed.rb文件
我有一个有图像列的模型.我正在使用CarrierWave上传图像(我正在关注此 rails cast来执行此操作.

现在,我想使用seed.rb文件创建一些默认记录,但我未能为图像提供正确的parh / url.

所以,我在List item app / public / images /文件夹中有图像,这是seed.rb文件中的代码:

gems = {

    test1: {

        name: 'test1',description: 'test1',image: '/public/images/test1.png',},test2: {

        name: 'test2',description: 'test2',image: '/public/images/test2.png'
}

gems.each do |user,data|

  gem = DemoGem.new(data)

  unless DemoGem.where(name: gem.name).exists?
    gem.save!
  end
end

当我运行rake db:seed命令时,我收到以下错误:

CarrierWave::FormNotMultipart: You tried to assign a String or a
Pathname to an uploader,for security reasons,this is not allowed.

谁能告诉我们如何为图像提供正确的网址?

解决方法

假设您的Gem模型将图像字段作为Carrierwave上传器(即,您的Gem模型中有mount_uploader:image,ImageUploader或类似物),您可以将ruby File对象分配给图像属性,而不是字符串.像这样的东西:
gem = Demogem.new(data)
image_src = File.join(Rails.root,"/public/images/test2.png")
src_file = File.new(image_src)
gem.image = src_file
gem.save

在整个代码中,您可以更改种子数据(因此哈希中的图像属性设置为File.new(File.join(Rails.root,“/ public / images / test1.jpg”))或更改构建新记录的方式,因此默认情况下它不使用图像:

gems.each do |user,data|
    gem = DemoGem.new(data.reject { |k,v| k == "image" })
    gem.image = new File(File.join(Rails.root,data["image"]))

    unless DemoGem.where(name: gem.name).exists?
        gem.save!
    end
end

CarrierWave wiki has some documentation on this,但它不是很广泛.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读