These models are defined with respect to a legacy database:
class VeType < ActiveRecord::Base
has_many :ve #plural defined as “ve”
self.primary_key = “typeID”
end
class Ve < ActiveRecord::Base
belongs_to :ve_type, :foreign_key => “TypeID”
self.table_name = “ve” #plural defined as
“ve”
self.primary_key = “veID”
end
This statement:
VeType.find(0).ve.Name
generates this result:
←[1m←[36mVeType Load (0.0ms)←[0m ←[1mEXEC sp_executesql N’SELECT
TOP (1) [ve_types].* FROM [ve_types] WHERE [ve_types].[typeID] = @0’,
N’@0 int’, @0 = 0←[0m [[“typeID”, 0]]
NoMethodError: ←[1m←[35mVe Load (0.0ms)←[0m EXEC sp_executesql
N’SELECT [ve].* FROM [ve] WHERE [ve].[ve_type_id] = 0’
undefined method Name' for #<ActiveRecord::Relation:0x1ff9620> from C:/Ruby193/lib/ruby/gems/1.9.1/gems/activerecord-3.2.1/ lib/active_record/relation/delegation.rb:45:in
method_missing’
from C:/Ruby193/lib/ruby/gems/1.9.1/gems/activerecord-3.2.1/
lib/active_record/associations/collection_proxy.rb:101:in
method_missing' from (irb):51 from C:/Ruby193/lib/ruby/gems/1.9.1/gems/railties-3.2.1/lib/ rails/commands/console.rb:47:in
start’
from C:/Ruby193/lib/ruby/gems/1.9.1/gems/railties-3.2.1/lib/
rails/commands/console.rb:8:in start' from C:/Ruby193/lib/ruby/gems/1.9.1/gems/railties-3.2.1/lib/ rails/commands.rb:41:in
<top (required)>’
from script/rails:6:in require' from script/rails:6:in
’
Shouldn’t the second select statement look like this:
SELECT [ve].* FROM [ve] WHERE [ve].[TypeID] = 0
I have other examples of this problem, where the declared foreign_key
name is ignored, and the select statement uses the “conventional”
form. I must be missing something, but what?
Thanks in advance for any suggesterd line of analysis.