简体   繁体   中英

Seeding a model with a paperclip image in ruby on rails

I am using Ruby on rails and alongside it paperclip for image storing and linking. It works fantastic.

I want to now use the rake db:seed facility and populate my seeds.rb file with 'Event' objects.

I am using the seeds file to populate other areas of my application using syntax like follows:

categories = Category.create([{ name: 'General'}, {name: 'Clubs'}, {name: 'For Mum'}, {name: 'Services'}])

This is populating simple Category model which only has 1 filed - name. How do I create a seed for a more complicated model such as my 'Event' model which also expects an image as part of it? Can I somehow have a seed images directory and load the file locally using seed?

Please can you show me an example of the solution to create a model instance with a Paperclip image field using the seeds rake file.

Thanks!

You can just create ActiveRecord Model as below.

# create Event record with paperclip file
Event.create(name: 'event1', photo: File.new("image/to/path.jpg"))

This is Event model:

class Event < ActiveRecord::Base
  has_attached_file :photo
end

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM