views:

21

answers:

1

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?

+1  A: 

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

vrsmn
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
seems that there are strange side effects since my column is called object_id and thus potentially conflicting with a native Ruby method
elasticsecurity