使用seed.rb文件创建记录时CarrierWave :: FormNotMultipart错误

问题描述 投票:9回答:3

我有一个有image列的模型。我正在使用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:您尝试将字符串或路径名分配给上传器,出于安全原因,这是不允许的。

任何人都可以告诉如何为图像提供正确的url

ruby-on-rails ruby ruby-on-rails-4 carrierwave
3个回答
16
投票

假设你的Gem模型有image字段作为Carrierwave上传器(也就是说,你的mount_uploader :image, ImageUploader模型中有Gem或类似物),你可以为你的File属性指定一个ruby image对象,而不是字符串。像这样的东西:

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

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

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,但它不是很广泛。


0
投票

这就是我对我的案子所做的事情:

["Sublime Text 3", "Internet Explorer"].each do |title|
  unless Post.exists?(title: title)
    post = Post.create!(title: title,
                        subtitle: "Subtitle of the #{title}",
                        content: "A sample post of the content about #{title}",
                        author: User.first)
    post.attachments_attributes = [file: Rails.root.join("spec/fixtures/photo.jpg").open]
    post.save!
  end
end

0
投票

将内容放在种子文件中的智能方法就像这样

Rails.root.join("#{Rails.root}/app/assets/images/image_a.jpg")
© www.soinside.com 2019 - 2024. All rights reserved.