Search code examples
ruby-on-railsrubyassociationsmodel-associationshas-one

Rails: How can this be done with a has_one association?


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


Solution

  • 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.