Rails Console / Active Record (ORM) Basics (Associations) 2

Associations:

Model -> Article

Table -> articles

foreign key (column in associated table, say comments) to reference this table -> article_id

class methods:

has_one (example: 1 User has 1 Profile)

example:

class User< ActiveRecord::Base

has_one :profile (table profiles has foreign key user_id)

end

class Profile < ActiveRecord::Base

belongs_to :user

end

in console

>>user = User.create(:email=>’user@example.com’,:password=>’secret’)

>>profile = Profile.create(:name=>’John Doe’,:bio=>’Ruby developer’)

>>user.profile = profile

or in one line

>>user.create_profile :name=>’John Doe’, :bio=>’Ruby developer’

methods added by has_one association:

user.profile

user.profile=(profile)

user.profile.nil?

user.build_profile(attributes={}) / not saved

user.create_profile(attributes={}) / saved

common has_one options:

:class_name

:conditions

:foreign_key

: order

:dependent

methods added by has_many and belongs_to associations:

user.articles

user.articles=(articles)

user.articles << article

user.articles.delete(article)

user.articles.empty?

user.articles.size

user.article_ids

user.articles.clear

user.articles.find

user.articles.build(attributes={})

user.articles.create(attributes={})

common has_many options:

:class_name

:conditions

:foreign_key

: order

:dependent

example:

class User < ActiveRecord::Base

attr_accessible :email, :password
has_one :profile
has_many :articles, : order => ‘published_at DESC, title ASC’, :dependent => :destroy

end

has_and_belongs_to_many (habtm)

example: articles to categories

neither ‘belongs_to’ strictly

join table created alphabetical, thus articles_categories

has_and_belongs_to_many :articles

Leave a Reply

You must be logged in to post a comment.