How to populate your table with default values in rails

I have a Roles table with :name and :long_name columns. I have only 4 types of roles, with name i.e. short name and long name; :tm => Team member, lm => Line manager, :hr => Human resource and :admin => Administrator. In order to populate the values in my Roles table, all I need to do is put the logic in my db/seeds.rb file and run the rake db:seed command.

seed.rb —

role_collection = { 
  :hr => 'Human Resource', 
  :tm => 'Team Member', 
  :lm => 'Line Manager', 
  :admin => 'Administrator' 
}
role_collection.each do |key, value|
  @a_role = { :name => key.capitalize, :long_name => value }
  Role.create(@a_role)
end

Command
rake db:seed

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s