Search code examples
ruby-on-railsrubyruby-on-rails-3.1bootrecords

How can I create records in database when application boot or restarted


In my application I have a sing_up_page which has a sing_up_form which has a drop_down_list Which shows the role_type.

RoleType is the class in application in which I have stored records

insert into role_type (id,name) values (1,'user');
insert into role_type (id,name) values (1,'admin');
insert into role_type (id,name) values (1,'vender');

manually in database before starting the application. Before moving to the sing_up_page I do

@role_type=RoleType.all

so that drop down can use it to display role_types but I want If their is a procedure to produce these records at the boot time of the application without manually creating records in database as in Groovy on Grails.


Solution

  • If you create a .rb file in app/config/initializers/, it will be executed when the server loads.

    Example:

    app/config/initializers/seed.rb

    %w{user admin vendor}.each do |role|
      RoleType.create(:name => role)
    end
    

    Every time the server loads, these records will be created.

    Question: why are these records not retained in your database? Are you or someone else deleting them?