Active Record
Automated Mapping
Automatically maps:
Tables → classes
Rows → objects (instances of model classes)
Columns → object attributes
Table to class mapping uses English plurals:
An
Invoice
model class maps to aninvoices
table.A
Person
model class maps to apeople
table.A
Country
model class maps to acountries
table.A
SecurityLevel
model class maps to asecurity_levels
table.
Learn more: http://api.rubyonrails.com/classes/ActiveRecord/Base.html
Associations
Four ways of associating models (see also Figures B-1 and B-2):
Figure B-1. One-to-one and one-to-many relationships
Figure B-2. Many-to-many relationships
has_one has_many belongs_to has_and_belongs_to_many def Order < ActiveRecord::Base has_many :line_items belongs_to :customer # there's a column "customer_id" in the db table end def LineItem < ActiveRecord::Base belongs_to :order # there's a column "order_id" in the db table end def Customer < ActiveRecord::Base has_many :orders has_one :address, :as => addressable end def Address < ActiveRecord::Base belongs_to :addressable, :polymorphic => true end belongs_to :some_model, :class_name => 'MyClass', # specifies other class name :foreign_key => 'my_real_id', # and primary key :conditions => 'column = 0' # only finds when this condition met :polymporphic => boolean # true if more than ...
Get Rails: Up and Running, 2nd Edition now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.