【发布时间】:2011-06-24 21:53:08
【问题描述】:
假设我有一个名为 server 的旧 MySQL 表,其中包含字段 serverid:integer 和
servername:string.
我创建了一个名为 action 的新表,其中包含:
t.integer :actionable_id
t.string :actionable_type
t.string :text
而且我希望这张表与旧版服务器有一个 poly 关系 表。
当我这样做时:
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
我尝试为给定的Action 获取Server:
ruby-1.9.2-p180-patched :013 > Action.first.actionable
我收到此错误:
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
如何让操作知道主键是serverid
而不是id,就像它知道这里的表名是一样的
server 而不是 servers?它不应该使用 set_primary_key 值吗?
这是多态关系错误吗?
编辑:应用下面的更改(添加primary_key)后,它适用于服务器关系,但我确信它会失败的其他关系。
class Action < ActiveRecord::Base
belongs_to :actionable, :polymorphic => true, :primary_key => 'serverid'
end
IMO,primary_key的值应该被目标的primary_key自动识别。
【问题讨论】:
标签: activerecord polymorphic-associations ruby-on-rails-3.1