Reputation: 900
I have 4 classes: User
, Platform
and Listing
and Item
.
User has many platforms.
Platform has many items through listings.
Listing belongs to item and belongs to platform.
Item has many listings.
How would I go about getting all the users items?
My existing solution (which involves an in-efficient in-memory solution) is this:
user.platforms.includes(:items).inject([]) { |result, x| result + x.items }
Upvotes: 0
Views: 553
Reputation: 76
You can use query started from Item
and use user.id
as parameter.
Item.joins(:platforms).where("platform.user_id = ?", user.id)
Upvotes: 0
Reputation: 76
You can add relation in your User
model. ActiveRecord will take care about your query.
class User < ActiveRecord::Base
has_many :platforms
has_many :items, through: :platforms
end
Upvotes: 1