Override Rails Uploader to seed database

流过昼夜 提交于 2019-12-29 08:02:27

问题


I have a CarrierWave rails uploader. I want to seed the database with fake users so I'm trying to add the images in with the same seed file. The images are in a common storage, so if I can just get the avatar strings in the database they'll work. When it saves the users though the image's aren't sticking.

# 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> 

回答1:


You will have to insert the data in the following way.

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

So the entire user create would look like

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

Related question




回答2:


Besides using open() as Nishant suggestions, you can also specify remote_avatar_url to manually set the remote 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"

Thanks to JosephJaber for suggesting this in Seeding file uploads with CarrierWave, Rails 3

I used this approach to populate some video URLs for CarrierWave Uploader in my seeds.rb




回答3:


To update the database directly and skip out on CarrierWave:

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


来源:https://stackoverflow.com/questions/14108154/override-rails-uploader-to-seed-database

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!