Rails Cheat Sheet

* From all the following cheat sheet consider the model name as Model

Create a new empty model

Model.new

Create an object with some params and save it.

Model.create( :field1 => “value1”, :field2 => 2 )

Just saving the model

Model.save

Search for a field = value and create if not found

Model.find_or_create_by_field( value )

Model.find_or_create_by_name_and_email( ‘John’, ‘john@example.com’)

4 ways of Model associations

  1. has_one: The normal one-to-one relationship
  2. has_many: one to many relationships
  3. belongs_to : Something belongs to some one
  4. has_belongs_to_many : has_many + belongs_to

model-relation

def Order < ActiveRecord::Base
has_many :line_items
belongs_to :customer
end

def LineItem < ActiveRecord::Base
belongs_to :order
end

def Customer < ActiveRecord::Base
has_many :orders
has_one :address
end

def Address < ActiveRecord::Base
belongs_to :customer
end

Model Relation

def Category < ActiveRecord::Base
has_and_belongs_to_many :products
end

def Product < ActiveRecord::Base
has_and_belongs_to_many :categories
end