I’m trying to join two tables with active record and not getting what I
expect *surprise*.
Two tables T1 and T2, both have a common key called ID. Given this
relationship in the Models
class T1 < ActiveRecord::Base
has_one :T2
class T1 < ActiveRecord::Base
belongs_to :T1
In the controller I have…
@results = T1.all(:joins => :T2)
@results only contains the columns from T1 and none from T2.
If I do a find_by_sql as follows
@results = T1.find_by_sql("select * from T1, T2 where T1.id = T2.id")
@results contains the correct Cartesian product of T1, T2.
I’m trying to join two tables with active record and not getting what I
expect *surprise*.
Two tables T1 and T2, both have a common key called ID. Given this
relationship in the Models
class T1 < ActiveRecord::Base
has_one :T2
class T1 < ActiveRecord::Base
belongs_to :T1
In the controller I have…
@results = T1.all(:joins => :T2)
@results only contains the columns from T1 and none from T2.
If I do a find_by_sql as follows
@results = T1.find_by_sql("select * from T1, T2 where T1.id = T2.id")
@results contains the correct Cartesian product of T1, T2.
Am I missing something in the active record call?
No; rather, you're missing something in the setup. Normally the foreign
key for t2 would be t1.t2_id , not simply t1.id .
I think your DB design has problems, frankly. You shouldn't normally be
trying to match the primary key in one table with the primary key in
another. What are you trying to achieve here?