0

My model has two columns, one named foo_id and the other bar_id.

I'm wondering if it's possible to turn these two simple methods into has_one associations:

class SomeModel < ActiveRecord::Base
  def foobar_foo
    Foobar.find( self.foo_id )
  end

  def foobar_bar
    Foobar.find( self.bar_id )
  end
end

Perhaps I've been staring at the documentation for too long, but I can't seem to find a way to tell Rails to use self.foo_id as the foreign key for the other model.

I'm aware that in most cases this should instead be a has_many :through or maybe a belongs_to, but for the sake of argument I'm interested to learn if this is possible with a has_one

Chris Salzberg
  • 27,099
  • 4
  • 75
  • 82
Marco
  • 4,345
  • 6
  • 43
  • 77

2 Answers2

0

Does this help?

has_one :foo, class_name: "Foobar", foreign_key: :foo_id
has_one :bar, class_name: "Foobar", foreign_key: :bar_id

http://api.rubyonrails.org/classes/ActiveRecord/Associations/ClassMethods.html#method-i-has_one

mickeyreiss
  • 490
  • 3
  • 13
0

Finally had a chance to revisit this problem and incidentally, stumbled across a solution within the first few minutes of trying..

  has_one :bar, primary_key: :bar_id, foreign_key: :id, class_name: 'Foobar'
  has_one :foo, primary_key: :foo_id, foreign_key: :id, class_name: 'Foobar'

Works as intended.

Marco
  • 4,345
  • 6
  • 43
  • 77