0

I'm not getting a concept (nothing new there) on how to scope a Active Record query. I want to only receive the records where there is a certain condition in a related record. The example I have happens to be polymorphic just in case that is a factor. I'm sure there is somewhere where this is explained but I have not found it for whatever reason.

My Models:

class User < ActiveRecord::Base
  belongs_to :owner, polymorphic: true
end

class Member < ActiveRecord::Base  
  has_one :user, as: :owner
end

I want to basically run a where on the Member class for related records that have a certain owner_id/owner_type.

Lets say we have 5 Members with ids 1-5 and we have one user with the owner_id set to 3 and the owner_type set to 'Member'. I want to only receive back the one Member object with id 3. I'm trying to run this in Pundit and thus why I'm not just going at it form the User side.

Thanks for any help as always!!!

MechDog
  • 508
  • 7
  • 18

1 Answers1

1

Based on your comment that you said was close I'd say you should be able to do:

Member.joins(:user).where('users.id = ?', current_user.id)

However based on how I'm reading your question I would say you want to do:

Member.joins(:user).where('users.owner_id = ?', current_user.id)

Assuming current_user.id is 3.

There may be a cleaner way to do this, but that's the syntax I usually use. If these aren't right, try being a little more clear in your question and we can go from there! :)

Saul
  • 911
  • 1
  • 8
  • 19
  • This appears to be working for now, just wonder if that is dumb luck;-) Member.joins(:user).where(users: {id: current_user.id }) I think that is the same as your first one correct? – MechDog Aug 21 '14 at 17:10
  • That is the same. The part of me that used to have to write raw SQL likes the string approach I used better, but yours will work as well :) – Saul Aug 21 '14 at 17:13