Skip to content

Instantly share code, notes, and snippets.

@amejiarosario
Created June 18, 2012 22:18
Show Gist options
  • Star 11 You must be signed in to star a gist
  • Fork 8 You must be signed in to fork a gist
  • Save amejiarosario/2951093 to your computer and use it in GitHub Desktop.
Save amejiarosario/2951093 to your computer and use it in GitHub Desktop.
Rails ActiveRecord (association) - Cheatsheet

Rails ActiveRecord (association) - Cheatsheet

http://guides.rubyonrails.org/association_basics.html

Types of associations

  • belongs_to : TABLE_NAME
  • has_one : TABLE_NAME [:through => :TABLE_NAME]
  • has_many : TABLE_NAME [:through => :TABLE_NAME]
  • has_and_belongs_to_many : TABLE_NAME [:join_table => :TABLE_NAME]

examples:

belongs_to :customer
has_one :account
has_many :appointments
has_many :patients, :through => :appointments
has_and_belongs_to_many :parts

belongs_to :imageable, :polymorphic => true
has_many :pictures, :as => :imageable

has_many :subordinates, :class_name => "Employee", :foreign_key => "manager_id"

belongs_to and has_one

given

class Customer < ActiveRecord::Base
  has_many :orders, :dependent => :destroy
end
 
class Order < ActiveRecord::Base
  belongs_to :customer
end

then

association(force_reload = false)  # e.g. @order.customer
association=(associate)            # e.g. @order.customer = @customer
build_association(attributes = {}) # e.g. @customer = @order.build_customer(:customer_number => 123,:customer_name => "John Doe")
create_association(attributes = {}) # e.g. @customer = @order.create_customer(:customer_number => 123,:customer_name => "John Doe")

has_many

collection(force_reload = false)
collection<<(object, …)
collection.delete(object, …)
collection=objects
collection_singular_ids
collection_singular_ids=ids
collection.clear
collection.empty?
collection.size
collection.find(…)
collection.where(…)
collection.exists?(…)
collection.build(attributes = {}, …)
collection.create(attributes = {})

has_many example

Given

class Customer < ActiveRecord::Base
  has_many :orders
end

Then you can say:

orders(force_reload = false)
@orders = @customer.orders

orders<<(object, ...)
@customer.orders << @order1

orders.delete(object, ...)
orders=objects

order_ids
order_ids=ids
@order_ids = @customer.order_ids

orders.clear

orders.empty?
@customer.orders.empty?

orders.size
@order_count = @customer.orders.size

orders.find(...)
@open_orders = @customer.orders.where(:open => 1)

orders.where(...)
@open_orders = @customer.orders.where(:open => 1)

orders.exists?(...)

orders.build(attributes = {}, ...)
@order = @customer.orders.build(:order_date => Time.now, :order_number => "A12345")

orders.create(attributes = {})
@order = @customer.orders.create(:order_date => Time.now,:order_number => "A12345")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment