It seems that when call a scope on a subclass using
set_table_name, where the scope is defined in the
parent class, results in using the table name of the parent.
Here is a basic script to repro the issue. This is on
ActiveRecord 3.0.3:
require "rubygems"
require "active_record"
ActiveRecord::Base.establish_connection(
:adapter => "sqlite3",
:dbfile => ":memory:",
:database => "test"
)
ActiveRecord::Schema.define do
create_table "people", :force => true do |t|
t.string "name", :null => false
end
create_table "children", :force => true do |t|
t.string "name", :null => false
t.string "favorite_toy", :null => false
end
end
class People < ActiveRecord::Base
scope :named, lambda { |name| where(:name => name) }
end
class Child < People
set_table_name "children"
end
People.create(:name => "Fred")
p People.named("Fred")
Child.create(:name => "Jonny", :favorite_toy => "Elmo")
p Child.named("Jonny")
Running it results in:
jeff ~ $ ruby ar_inheritance_test.rb
-- create_table("people", {:force=>true})
-> 0.2486s
-- create_table("children", {:force=>true})
-> 0.0079s
[#<People id: 1, name: "Fred">]
/opt/local/lib/ruby/gems/1.8/gems/activerecord-3.0.3/lib/active_record/connection_adapters/abstract_adapter.rb:202:in `log': SQLite3::SQLException: no such column: people.name: SELECT "children".* FROM "children" WHERE ("people"."name" = 'Jonny') (ActiveRecord::StatementInvalid)
from /opt/local/lib/ruby/gems/1.8/gems/activerecord-3.0.3/lib/active_record/connection_adapters/sqlite_adapter.rb:135:in `execute'
from /opt/local/lib/ruby/gems/1.8/gems/activerecord-3.0.3/lib/active_record/connection_adapters/sqlite_adapter.rb:284:in `select'
from /opt/local/lib/ruby/gems/1.8/gems/activerecord-3.0.3/lib/active_record/connection_adapters/abstract/database_statements.rb:7:in `select_all'
from /opt/local/lib/ruby/gems/1.8/gems/activerecord-3.0.3/lib/active_record/connection_adapters/abstract/query_cache.rb:56:in `select_all'
from /opt/local/lib/ruby/gems/1.8/gems/activerecord-3.0.3/lib/active_record/base.rb:467:in `find_by_sql'
from /opt/local/lib/ruby/gems/1.8/gems/activerecord-3.0.3/lib/active_record/relation.rb:64:in `to_a'
from /opt/local/lib/ruby/gems/1.8/gems/activerecord-3.0.3/lib/active_record/relation.rb:356:in `inspect'
from ar_inheritance_test.rb:37:in `p'
from ar_inheritance_test.rb:37
I believe the SQL generated should be:
SELECT "children".* FROM "children" WHERE ("children"."name" = 'Jonny')