使用 Primary_key+foreign_key 选项关联的 Rails 问题

发布于 2024-09-08 13:57:12 字数 573 浏览 7 评论 0原文

我想从 Rails 访问旧数据库模式。我有一张带有主键 OBJECT_ID 的表 NAGIOS_OBJECTS 和一张引用带有 HOST_OBJECT_ID 列的 NAGIOS_OBJECTS 的表 NAGIOS_HOST_CHECKS。因此,我将关系定义如下:

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 时,我总是得到 nil。

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

I want to access a legacy database schema from Rails. I have one table NAGIOS_OBJECTS with a primary key OBJECT_ID and one table NAGIOS_HOST_CHECKS that refers to NAGIOS_OBJECTS with a column HOST_OBJECT_ID. I thus defined the relations as follows:

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

However, when calling a_nagios_object.nagios_host_check or a_nagios_host_check.nagios_object, I always get nil.

Any idea what is wrong with my code?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

泅人 2024-09-15 13:57:12

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

foreign_key and primary_key should be strings, not symbols

ex:

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文