Skip to content

Instantly share code, notes, and snippets.

@andyjeffries
Created March 5, 2010 13:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save andyjeffries/322710 to your computer and use it in GitHub Desktop.
Save andyjeffries/322710 to your computer and use it in GitHub Desktop.
# MIGRATION
class CreateBasicTables < ActiveRecord::Migration
def self.up
create_table :books, :force => true do |t|
t.string :title
t.timestamps
end
create_table :authors, :force => true do |t|
t.string :name
t.timestamps
end
create_table :roles, :force => true do |t|
t.integer :author_id
t.integer :book_id
t.string :role_type
t.timestamps
end
end
def self.down
drop_table :roles
drop_table :authors
drop_table :books
end
end
# MODELS
class Role < ActiveRecord::Base
belongs_to :author
belongs_to :book
end
class Book < ActiveRecord::Base
has_many :authors, :through => :roles
has_many :roles
end
class Author < ActiveRecord::Base
has_many :books, :through => :roles
has_many :roles
end
# USAGE
b = Book.create(:title => "Beginning FooBar Programming")
a = Author.create(:name => "John SMITH")
r = Role.create(:book => b, :author => a, :role_type => "MAIN_AUTHOR")
b.authors
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment