I keep forgetting all those fancy ruby on rails commands and the important code snippets always. I better keep them documented some where I can find easily. So I’m going to write down as much as code snippets, command lines, tips tricks where I need. Anyway this looks messy as I update this page time to time, hope you also can contribute for the list. I hope this will help someone else too.
How to add/remove new columns to table (models) ?
you can specify columns you want to add/remove in your migration by passing attribute:type pairs to the migration generator command line. here is an example to add the mobile number to existing user model.
[randika@localhost MyApp]$ script/generate migration AddMobileToUser mobile:string
and run the rake db:migrate command. This will create the migration schema for you as:
class AddMobileToUser < ActiveRecord::Migration def self.up add_column :users, :mobile, :string end def self.down remove_column :users, :mobile end end
Similarly when you need to remove a column try using below command, followed by the the rake db:migrate
[randika@localhost MyApp]$ script/generate migration RemoveMobileFromUser mobile:string
How to create dynamic drop down menu from a another model
<%= f.select :country_id, Country.all.collect {|country| [ country.name, country.id ] } %>
this will output:
<select id="country_country_id" name="country[country_id]"> <option value="1">Country A</option> <option value="2">Country B</option> <option value="3">Country C</option> </select>
How to find the configuration settings, versions of the development environment
- To determine the version of Rails that you are running, you can issue
rails -vat a command prompt.
$rails -v
which rails at a command prompt. (only on linux)$which rails
gem list$gem list
How to print the month name from a month number
Putting this code in a view, will print “December” as the output.
<%= Date::MONTHNAMES[12] %>
How to assign a css class to link_to method in Ruby on Rails
How to install/start mongrel http server
$ sudo gem install mongrel $ cd yourrailsapp $ mongrel_rails start -d
How to stop mongrel http server
$ mongrel_rails stop