[英]how to reference to an image in seeds.rb
我使用Carrierwave上传与我的用户模型关联的图像,该模型具有对应的picture
属性,该属性在字符串字段中包含图像文件的名称。 通常,上传图片的名称存储在public/uploads
。
现在,我想用示例用户(包括个人资料图片的关联路径)为开发数据库添加种子。 我尝试将我的pic1.jpg
, pic2.jpg
, pic3.jpg
图片存储在public/images
并在db/seeds.rb
引用这些图片作为picture: '/images/pic1.jpg'
db/seeds.rb
picture: '/images/pic1.jpg'
等,就像Grant Neufeld在一个老的stackoverflow问题 。 在视图中,使用以下代码包含了图片:
<%= image_tag @user.picture.url if @user.picture? %>
但是,这不起作用,因为picture属性为nil,所以图像未加载到视图中。 我还尝试将我的图片存储在app/assets/images
,并将它们引用为db/seeds.rb
picture: 'pic1.jpg'
, picture: 'pic2.jpg'
, picture: 'pic3.jpg'
。
以下是我的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'))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.