Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 660
RenegadeAndy Avatar asked Feb 10 '23 23:02

RenegadeAndy


1 Answers

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
like image 155
shoji Avatar answered Feb 23 '23 21:02

shoji