Let’s say I have a legacy MySQL table called server with fields serverid:integer and
servername:string.
I created a new table called action that will have:
t.integer :actionable_id
t.string :actionable_type
t.string :text
And I want this table to have a poly relationship with the legacy server
table.
When I do this:
class Server < ActiveRecord::Base
set_table_name "server"
set_primary_key "serverid"
has_many :actions, :as => :actionable, :foreign_key => 'serverid'
end
class Action < ActiveRecord::Base
belongs_to :actionable, :polymorphic => true
end
And I try to get the Server for a given Action:
ruby-1.9.2-p180-patched :013 > Action.first.actionable
I get this error:
Mysql2::Error: Unknown column 'server.id' in 'where clause': SELECT
`server`.* FROM `server` WHERE `server`.`id` = 10 LIMIT 1
ActiveRecord::StatementInvalid: Mysql2::Error: Unknown column
'server.id' in 'where clause': SELECT `server`.* FROM `server` WHERE
`server`.`id` = 10 LIMIT 1
How can I make the Action be aware that the primary key is serverid
and not id, the same way it is aware that the table name here is
server and not servers? Shouldn’t it use the set_primary_key value?
Is this a Polymorphic relationship bug?
EDIT: After applying the change below (adding primary_key), it works for the Server relation, but I am sure it will fail for the other relations.
class Action < ActiveRecord::Base
belongs_to :actionable, :polymorphic => true, :primary_key => 'serverid'
end
IMO, the value of primary_key should be automatically recognized by the target’s primary_key.
Kolrie,
We had the same problem at my shop. Our solution was pretty straight forward. We simply defined a method that was named the same as the polymorphic relationship. So in your case you would define a method called actionable and do the following:
Not sure if that’d work for you, but it’s a good work around until the Rails app is fixed to support overriding primary_keys while using polymorphic relationships.