Drew
Drew

Reputation: 2663

Selecting Fields From Multiple Tables

Is there a way to write this query in rails other than by using the execute method?

connection.execute("select value_1, value_2, value_3 from table1 join table2 on table2.table1_id = table1.id where table2.table3_id = table3_id_value")

Upvotes: 1

Views: 1317

Answers (1)

Gene
Gene

Reputation: 46960

It's far easier if you bend to the Rails conventions for pluralizing and capitalizing names.

Then if table1 is really foos and table2 is bars corresponding to Active Record Foo and Bar, declarations, you'd want

belongs_to :foo

in the Bar record. This corresponds to a foreign key foo_id. Then add matching

has_many :bars

in the Foo record. This allows retrieving all the bars records that reference foo with foo.bars. With all this in place, the query would be

Foo.join(:bar).select(:value_1, :value_2, :value_3)
   .where('bars.table3_id = ?, table3_id_value)

It's possible to override the default conventions for table and foreign key names. Look up the correct options in the Active Record query documentation.

Upvotes: 1

Related Questions