如何引用seeds.rb中的图像
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了如何引用seeds.rb中的图像相关的知识,希望对你有一定的参考价值。
我使用Carrierwave上传与我的User模型相关联的图像,该模型具有相应的picture
属性,该属性包含字符串字段中图像文件的名称。通常,上传图片的名称存储在public/uploads
中。
现在,我想用样本用户来开发我的开发数据库,包括相关的配置文件图片路径。我试图在pic1.jpg
存储我的pic2.jpg
,pic3.jpg
,public/images
图片,并参考db/seeds.rb
中的这些图片作为picture: '/images/pic1.jpg'
等,就像Grant Neufeld在old stackoverflow question中提出的那样。在视图中使用以下代码包含图片:
<%= image_tag @user.picture.url if @user.picture? %>
但是这不起作用,图像未加载到视图中,因为图片属性为零。我还尝试将我的照片存储在app/assets/images
中,并将它们作为picture: 'pic1.jpg'
,picture: 'pic2.jpg'
,picture: 'pic3.jpg'
在db/seeds.rb
中引用而没有结果。
下面是我的db/seeds.rb
文件:
User.create!(name: "Example User",
email: "example@railstutorial.org",
password: "foobar",
password_confirmation: "foobar",
admin: true,
politics: 'left',
car: true,
pets: 'I like horses and bears',
music: 'American country and folk',
picture: 'pic1.jpg',
profile: 'I like music and the Ruby and Python programming languages',
activated: true,
activated_at: Time.zone.now)
User.create!(name: "Super-friendly User",
email: "example-101@railstutorial.org",
password: "PassWord-0",
password_confirmation: "PassWord-0",
admin: true,
smoker: true,
politics: 'left',
car: true,
pets: 'I like turtles and whales',
car_pets: true,
music: 'Jazz and blues',
picture: 'pic2.jpg',
profile: 'I like music and drinking',
activated: true,
activated_at: Time.zone.now)
User.create!(name: "Friendly User",
email: "example-102@railstutorial.org",
password: "PassWord-0",
password_confirmation: "PassWord-0",
politics: 'right',
car: true,
pets: 'I like snakes and gorillas',
music: 'pop and classics',
picture: 'pic3.jpg',
profile: 'I like music and hiking',
activated: true,
activated_at: Time.zone.now)
99.times do |n|
name = Faker::Name.name
email = "example-#{n+1}@railstutorial.org"
password = "password"
User.create!(name: name,
email: email,
password: password,
password_confirmation: password,
activated: true,
activated_at: Time.zone.now)
end
假设您在public/images
下保存图像,Carrierwave要求您将IO对象传递给Rails模型,因此要在seeds.rb
文件中正确设置它,您需要执行以下操作:
User.create!(
name: "Example User",
email: "example@railstutorial.org",
password: "foobar",
password_confirmation: "foobar",
admin: true,
politics: 'left',
car: true,
pets: 'I like horses and bears',
music: 'American country and folk',
picture: File.open(Rails.root.join('public', 'images', 'pic1.jpg')),
profile: 'I like music and the Ruby and Python programming languages',
activated: true,
activated_at: Time.zone.now
)
看到我把picture
改为File.open(Rails.root.join('public', 'images', 'pic1.jpg'))
以上是关于如何引用seeds.rb中的图像的主要内容,如果未能解决你的问题,请参考以下文章