many to many relationship rails models code example

Example 1: rails many to many relationship same model

class Page < ActiveRecord::Base

  has_many :left_page_associations, :foreign_key => :left_page_id,
           :class_name => 'PageAssociation'
  has_many :left_associations, :through => :left_page_associations,
           :source => :right_page
  has_many :right_page_associations, :foreign_key => :right_page_id,
           :class_name => 'PageAssociation'
  has_many :right_associations, :through => :right_page_associations,
           :source => :left_page

  def associations
    (left_associations + right_associations).flatten.uniq
  end

end

Example 2: rails many to many relationship same model

class PageAssociation < ActiveRecord::Base

  belongs_to :left_page, :class_name => 'Page'
  belongs_to :right_page, :class_name => 'Page'

end

Example 3: rails many to many relationship same model

class Page < ActiveRecord::Base

  has_many :left_page_associations, :foreign_key => :left_page_id,
           :class_name => 'PageAssociation'
  has_many :left_associations, :through => :left_page_associations,
           :source => :right_page
  has_many :right_page_associations, :foreign_key => :right_page_id,
           :class_name => 'PageAssociation'
  has_many :right_associations, :through => :right_page_associations,
           :source => :left_page

end

Tags:

Ruby Example