Skip to content

Instantly share code, notes, and snippets.

@mwmitchell
Created July 30, 2011 17:20
Show Gist options
  • Save mwmitchell/1115764 to your computer and use it in GitHub Desktop.
Save mwmitchell/1115764 to your computer and use it in GitHub Desktop.
class PageCategory < ActiveRecord::Base
belongs_to :page
belongs_to :category
validates_presence_of :page_id
validates_presence_of :category_id
end
class Category < ActiveRecord::Base
has_many :page_categories, :dependent => :destroy
has_many :pages, :through => :page_categories
end
class Page < ActiveRecord::Base
has_many :page_categories, :dependent => :destroy
has_many :categories, :through => :page_categories
end
# example 1
c = Category.new(:name => "blah")
c.save
p = Page.new(:title => "my page", :categories => [c])
p.save
# this yields []
c.pages.inspect
################
# example 2
c = Category.new(:name => "blah")
c.save
p = Page.new(:title => "my page")
p.categories << c
p.save
# this yields []
c.pages.inspect
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment