Reputation: 5434
I have a resource called User
, and it has_many
Session
s. A Session
has_many
Items
. I'm using Rails and need an ActiveRecord call to list all the Item
s that a user has. How would I do that? I don't know how to fetch all the indirectly associated records (not sure what's the right term).
Upvotes: 0
Views: 27
Reputation: 6253
other alternative, if you already set user model with has_many sessions then you can add has_many through with sample code below and each user can access items
class User < ApplicationRecord
has_many :sessions
has_many :items, through: :sessions
# this additional settings so user dan access items directly
end
@user = User.first
@items = @user.items
Upvotes: 1
Reputation: 20263
Assuming
Item
belongs to Session
Item
has session_id
User
called @user
Then try:
Item.where(session: @user.sessions)
Upvotes: 0