我使用Carrierwave上传了与我的用户模型关联的图像,该图像具有对应的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? %>
但是这不起作用,因为picture属性为nil,所以图像没有加载到视图中。我还尝试将图片存储在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
答案 0 :(得分:4)
假设您将图像保存在public/images
下,那么Carrierwave要求您将IO对象传递给Rails模型,因此您需要执行以下操作在seeds.rb
文件中正确设置它:< / p>
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'))