0

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?

elasticsecurity
  • 1,041
  • 1
  • 11
  • 11

1 Answers1

2

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

x0rist
  • 625
  • 4
  • 9
  • Thanks. That solved it! However, when creating a nagios_host_check object using NagiosHostCheck.create(:nagios_object => NagiosObject.create()), it doesn't retrieve the right id. Instead, I need to do NagiosHostCheck.create(:host_object_id => NagiosObject.create().id) – elasticsecurity Jul 05 '10 at 19:45
  • seems that there are strange side effects since my column is called object_id and thus potentially conflicting with a native Ruby method – elasticsecurity Jul 05 '10 at 20:33
  • @elasticsecurity I think you're right, the issue lies in that `:object_id` means something special to Rails/Ruby and using strings gets around that issue. But `foreign_key` and `primary_key` do not **need** to be assigned to `Strings`. I prefer using symbols, it's cleaner and more consistent with the rest of Rails assignments. – Joshua Pinter Sep 22 '14 at 17:54