-1

I have a Category model and an Article model. The association is set up so a Category has many articles. A regular user should not be able to create a user.

I was wondering, is there any way in Rails for me to automatically create instances of Category (eg. "Sports", "Entertainment") without doing it in the console or filling in a form? I know one way is setting up admins, but is there a simpler way?

kwngo
  • 9
  • 1
  • 3

1 Answers1

0

You can use the db/seeds.rb file. You have full access to all classes and methods of your application. So you can do:

Category.delete_all #avoid duplicates
Category.create(name: 'cat1')
Category.create(name: 'cat2')
#and so on

After writing that on seeds.rb, just call rake db:seed and it populates the db.

Since it's just a plain Ruby file, you can do a lot of things with it, for example, populate the categories only in production environment:

def populate_categories
  Category.create(name: 'cat1')
end

case Rails.env
  when "development"
   #do something else
  when "production"
   populate_categories

end
Tiago Farias
  • 3,397
  • 1
  • 27
  • 30
  • Thanks tiago. For future reference, [link](http://www.xyzpub.com/en/ruby-on-rails/3.2/seed_rb.html) and [link](http://edgeguides.rubyonrails.org/active_record_migrations.html) explains more about Seed data – kwngo Aug 19 '14 at 14:39