Skip to content

Instantly share code, notes, and snippets.

@fernandes
Last active August 29, 2015 14:19
Show Gist options
  • Save fernandes/43346ae8706e94d09fea to your computer and use it in GitHub Desktop.
Save fernandes/43346ae8706e94d09fea to your computer and use it in GitHub Desktop.
Rails Guides ActiveRecord Examples
# If for any reason you need to reproduce the Rails Guides ActiveRecord examples
# this gist will make your life easier
#############################
### Has Many / Belongs To ###
#############################
# be rails g model Order order_date:datetime customer:references
class Order < ActiveRecord::Base
belongs_to :customer
end
# be rails g model Customer name:string
class Customer < ActiveRecord::Base
has_many :orders
end
#################################
### Has One / Has One Through ###
#################################
# be rails g model Suplier name:string
class Supplier < ActiveRecord::Base
has_one :account
has_one :account_history, through: :account
end
# be rails g model Account account_number:string suplier:references
class Account < ActiveRecord::Base
belongs_to :supplier
has_one :account_history
end
# be rails g model AccountHistory credit_rating:integer account:references
class AccountHistory < ActiveRecord::Base
belongs_to :account
end
#######################
### Has ManyThrough ###
#######################
# be rails g model Physician name:string
class Physician < ActiveRecord::Base
has_many :appointments
has_many :patients, through: :appointments
end
# be rails g model Appointment appointment_date:datetime physician:references patient:references
class Appointment < ActiveRecord::Base
belongs_to :physician
belongs_to :patient
end
# be rails g model Patient name:string
class Patient < ActiveRecord::Base
has_many :appointments
has_many :physicians, through: :appointments
end
###############################
### Has And Belongs To Many ###
###############################
# be rails g model Assembly name:string
class Assembly < ActiveRecord::Base
has_and_belongs_to_many :parts
end
# be rails g model Part part_number:string
class Part < ActiveRecord::Base
has_and_belongs_to_many :assemblies
end
# You need a table for this association
# be rails g migration CreateAssembliesPartsJoinTable assemblies parts
###############################
### Plymorphic Associations ###
###############################
# be rails g model Picture name:string imageable:references{polymorphic}:index
class Picture < ActiveRecord::Base
belongs_to :imageable, polymorphic: true
end
# be rails g model Employee name:string
class Employee < ActiveRecord::Base
has_many :pictures, as: :imageable
end
# be rails g model Product name:string
class Product < ActiveRecord::Base
has_many :pictures, as: :imageable
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment