Rails使用primary_key + foreign_key选项发出关联问题

时间:2010-07-05 17:53:10

标签: ruby-on-rails primary-key legacy-database

我想从Rails访问旧数据库架构。我有一个表NAGIOS_OBJECTS与主键OBJECT_ID和一个表NAGIOS_HOST_CHECKS引用NAGIOS_OBJECTS与列HOST_OBJECT_ID。因此,我将关系定义如下:

class NagiosObject < ActiveRecord::Base
  has_one :nagios_host_check, :foreign_key => :host_object_id, :primary_key => :object_id
end

class NagiosHostCheck < ActiveRecord::Base
  belongs_to :nagios_object, :foreign_key => :host_object_id, :primary_key => :object_id
end

然而,当调用a_nagios_object.nagios_host_check或a_nagios_host_check.nagios_object时,我总是没有。

知道我的代码有什么问题吗?

1 个答案:

答案 0 :(得分:2)

foreign_key和primary_key应该是字符串,而不是符号

例如:

class NagiosObject < ActiveRecord::Base
  has_one :nagios_host_check, :foreign_key => 'host_object_id', :primary_key => 'object_id'
end

http://api.rubyonrails.org/classes/ActiveRecord/Associations/ClassMethods.html#M001317