I have a model called Listing:
class Listing < ActiveRecord::Base
belongs_to :user
end
I want to retrieve 100 listings along with each listing's user as a sub-hash within the listing hash, all with a single SQL call using ActiveRecord. This is how I'm doing it now directly with PostgreSQL:
def listings
listings = ActiveRecord::Base.connection.execute("select row_to_json(t) as listing from (select *, row_to_json(users) as user from listings INNER JOIN users ON listings.user_id = users.id LIMIT 100) t")
render json: {listings:listings,listing_count:Listing.count}
end
No looping over listings to retrieve their user, this is very time consuming. Thanks!
EDIT
I tried this as suggested but it is NOT returning the user:
2.2.1 :012 > Listing.joins(:user).limit(1)
Listing Load (0.6ms) SELECT "listings".* FROM "listings" INNER JOIN "users" ON "users"."id" = "listings"."user_id" LIMIT 1
=> #<ActiveRecord::Relation [#<Listing id: 1, user_id: 1, deleted: false, rent: "$950", deposit: "$950", availability: "6/18/2015", min_duration: "11", male_count: "0", female_count: "1", longitude: "-73.9767700960917", latitude: "40.75831025967895", location: "Midtown Center", comments: "Sequi acidus utor sublime cito autus suasoria. Ips...", photos: "1.jpg, 2.jpg, 3.jpg", cat: false, dog: false, doorman: true, large_room: true, apartment: true, house: false, garden: true, personal_bathroom: false, dog_friendly: true, cat_friendly: false, laundry: false, gym: true, elevator: true, renovated: true, furnished: false, smoking: true, smoke_free: false, air_conditioning: false, utilities_included: true, four_twenty_friendly: false, gay_friendly: false, vegan_friendly: false, vegetarian: true, kosher: false, girls_only: false, guys_only: true, created_at: "2015-07-17 20:09:21", updated_at: "2015-07-17 20:09:21">]>