0

I have a model that has :

Class Bar < ActiveRecord::Base
#...
belongs_to :foo_A, :class_name => "Foo"
belongs_to :foo_B, :class_name => "Foo"

And I would like to fetch information from table Foo as follows (code will not work):

Bar.joins(:foo_A, :foo_B).select("bars.*, foos_a.name as foo_a_name, foos_b.name as foo_b_name").all

Of course, there's no foos_a or foos_b table... just the foos table.

Is there a way to do it without writing the whole sql query ?

Thanks

user1251614
  • 529
  • 3
  • 11

1 Answers1

0

You must set the foreign_key for each belongs_to. See more in Same Model for Two belongs_to Associations

belongs_to :foo_A, :class_name => "Foo", :foreign_key => 'foo_a_id'
belongs_to :foo_B, :class_name => "Foo", :foreign_key => 'foo_b_id'
Community
  • 1
  • 1
mabarroso
  • 659
  • 2
  • 11
  • 23
  • Thank you for your answer. However, I have no problem with the association, just with the query I should use when joining the foos table so I can get the name of both foo_a and foo_b. – user1251614 Sep 09 '12 at 15:48