Skip to content

Instantly share code, notes, and snippets.

@denyago
Forked from tilo/rails_issue_5057.rb
Last active January 1, 2016 12:19
Show Gist options
  • Save denyago/8144000 to your computer and use it in GitHub Desktop.
Save denyago/8144000 to your computer and use it in GitHub Desktop.
Minimal ActiveRecord setup with SQlite3
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