2

I have two models/tables A and B. I'd like to perform an Active Record query where the results include columns from both tables. I tried inner joins as they sounded like they combine columns from both tables. However trying the Active Record joins finder method returns results from only the first table.

What Active Record queries include columns from two tables in the results? Perhaps the includes finder method could help.

Edit: think of the two tables as ForumThreads and Posts. Each forum thread has multiple posts. I'd like the rows in the query results to contain information for each post and information for the forum thread (for example the thread title).

This question might have answered my question: Rails Joins and include columns from joins table

Community
  • 1
  • 1
SundayMonday
  • 19,147
  • 29
  • 100
  • 154
  • 2
    Can you be more specific on what you're trying to do? `includes` will eager-load the data. But `ActiveRecord` will hide those results from you and just return the parent objects in an array. The `relationships` are loaded but you don't see them in the results. Elaborate on how you're trying to use the data just a little. – Azolo Feb 06 '12 at 21:24
  • @Azolo updated the question with more information. – SundayMonday Feb 06 '12 at 21:28
  • 1
    @Gazler got it, use `include` – Azolo Feb 06 '12 at 21:31

1 Answers1

9

Joins performs an inner join, but will not return the data until you ask for it.

User.where(:id => 1).joins(:client_applications)
User Load (0.2ms)  SELECT "users".* FROM "users" INNER JOIN "client_applications" ON "client_applications"."user_id" = "users"."id" WHERE "users"."id" = 1

Includes will execute two queries (using where in) and cache the associated data (Eager Loading)

User.where(:id => 1).includes(:client_applications)
User Load (0.4ms)  SELECT "users".* FROM "users" WHERE "users"."id" = 1
  ClientApplication Load (13.6ms)  SELECT "client_applications".* FROM "client_applications" WHERE "client_applications"."user_id" IN (1)
Gazler
  • 83,029
  • 18
  • 279
  • 245
  • I've tried using `includes` but the query results still have columns from only the first table. Please post an example query w/ results from both tables. – SundayMonday Feb 06 '12 at 22:24
  • 1
    @MrMusic You still need to request the resources. In my above example, you could do `users = User.where(:id => 1).includes(:client_applications)` And then when you want the client applications, you can do `users.first.client_applications` and it will retrieve them from the cached results from your initial query. – Gazler Feb 06 '12 at 22:27