Search code examples
ruby-on-railsassociationsinstances

Is there any way to create a new Category instance automatically when launching app?


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?


Solution

  • 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