Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails convention for table with just one row

Is there any conventions of rails or a right way to create/manipulate a table that will contain just one row? If not, what is the best way to do that? I need a way to store configurations of the system.

Thanks.

like image 340
William Weckl Avatar asked Sep 03 '14 13:09

William Weckl


1 Answers

Edited:

The rake db:seed command, basically execute whatever code you write in db/seeds.rb file of your application. Though can write any code in this file, by convention you should write code which populate your database with the basic data,

for example: when ever your deploy your application somewhere, and create a new database for it, you want that user with admin credential must be present there. So you will write the code which create that user in this file. Below is the sample code which will create a user and assign admin role to him.

puts "********Seeding Data Start************"

admin = User.create(:first_name => 'System', :last_name => 'Admin', 
       :email => '[email protected]', :password => 'sunpoweradmin', 
       :password_confirmation => 'sunpoweradmin', :source_system_id => 'systemadmin', 
       :source_system => 'LP',:entity_type => "Customer", :target_system => "OPENAM")

if admin.errors.blank?
    puts "***User #{admin.first_name} #{admin.last_name} created ***"
    admin.add_role :admin # add_role is method defined by rolify gem
    puts "***admin role assigned to #{admin.first_name} #{admin.last_name}***"
else
    puts "admin user failed to create due to below reasons:"
    admin.errors.each do |x, y|
       puts"#{x} #{y}" # x will be the field name and y will be the error on it
     end
end

puts "********Seeding Data End************"

Now whenever you recreate your database, you just need to run below command to populate the database, with the basic data

$ rake db:seed RAILS_ENV=production

The correct order to setup database in production, with all the rake task available within db namespace is as below

$rake db:create RAILS_ENV=production

$rake db:migrate RAILS_ENV=production

$ rake db:seed RAILS_ENV=production

NOTE: You can replace the first two commands with $rake db:setup RAILS_ENV=production , it will run both create and migrate internally


OR

You could use the rails-settings-cached gem which is a fork of the rails-settings gem

Once setup, you'll be able to do things such as:

Setting.foo = 123
Setting.foo # returns 123

Hope this may help you or what you are looking for..

like image 67
Gagan Gami Avatar answered Oct 02 '22 22:10

Gagan Gami