覆盖Rails上传器以播种数据库

时间:2013-01-01 05:53:35

标签: ruby-on-rails carrierwave

我有一个CarrierWave rails上传器。我想用假用户播种数据库,所以我试图用相同的种子文件添加图像。图像在一个共同的存储空间中,所以如果我能在数据库中获取头像字符串,它们就可以工作。当它保存用户时,虽然图像没有粘附。

# db/seeds.rb
user1 = User.create :email => "test1@test.com", :password => "testing", :name => "Bob Dylan", :avatar => "v1357014344/bdylan.jpg"
user1.save

# IRB
User.first
=> #<User id: 1, email: "test1@test.com", name: "Bob Dylan", avatar: nil> 

> a = User.first
> a.avatar = "v1357014344/bdylan.jpg"
> a.save
 (10.7ms)  commit transaction
=> true 
> a
=> #<User id: 1, email: "test1@test.com", name: "Bob Dylan", avatar: nil> 

3 个答案:

答案 0 :(得分:4)

您必须按以下方式插入数据。

File.open(File.join(Rails.root, 'test.jpg'))

所以整个用户创建看起来像

User.create :email => "test1@test.com", :password => "testing", :name => "Bob Dylan", :avatar => open("v1357014344/bdylan.jpg")

Related question

答案 1 :(得分:3)

除了使用open()作为Nishant建议外,您还可以指定remote_avatar_url来手动设置远程网址。

User.create :email => "test1@test.com", :password => "testing", :name => "Bob Dylan", :remote_avatar_url => "http://upload.wikimedia.org/wikipedia/commons/2/28/Joan_Baez_Bob_Dylan_crop.jpg"

感谢JosephJaberSeeding file uploads with CarrierWave, Rails 3

中提出建议

我使用这种方法在我的种子中为CarrierWave Uploader填充了一些视频网址.rb

答案 2 :(得分:1)

直接更新数据库并跳过CarrierWave:

model[:attribute] = 'url.jpg'
model.save