Jack
Jack

Reputation: 5434

How to get table one removed ActiveRecord

I have a resource called User, and it has_many Sessions. A Session has_many Items. I'm using Rails and need an ActiveRecord call to list all the Items 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

Answers (2)

widjajayd
widjajayd

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

jvillian
jvillian

Reputation: 20263

Assuming

  • Item belongs to Session
  • Item has session_id
  • You have an instance of User called @user

Then try:

Item.where(session: @user.sessions)

Upvotes: 0

Related Questions