Skip to content

Instantly share code, notes, and snippets.

@tilo
Created February 16, 2012 19:20
Show Gist options
  • Save tilo/1847117 to your computer and use it in GitHub Desktop.
Save tilo/1847117 to your computer and use it in GitHub Desktop.
Script for Rails Issue #5057
gem 'rails', '3.2.1'
require 'active_record'
puts "Active Record #{ActiveRecord::VERSION::STRING}"
ActiveRecord::Base.establish_connection(
:adapter => 'sqlite3',
:database => ':memory:'
)
# minimal DB Schema
ActiveRecord::Schema.define do
create_table "authors", :force => true do |t|
t.string "name"
end
create_table "authorships", :force => true do |t|
t.integer "author_id"
t.integer "book_id"
t.string "role"
end
create_table "books", :force => true do |t|
t.string "name"
end
end
# minimal models
class Author < ActiveRecord::Base
has_many :authorships
has_many :books , :through => :authorships
end
class Authorship < ActiveRecord::Base
belongs_to :author
belongs_to :book
end
class Book < ActiveRecord::Base
has_many :authorships
has_many :authors, :through => :authorships
has_many :main_authors, :through => :authorships, :source => :author,
:conditions => { :authorships => { :role => :main_author }}
end
b = Book.create(:name => "Programming Ruby")
dave = b.main_authors.create(:name => "David Thomas") # this should set the :role in the Authorships model
if dave.authorships.first.role.nil?
puts ":role not set in join-model Authorships"
end
puts dave.authorships.first.inspect
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment