Haseeb Ahmad
Haseeb Ahmad

Reputation: 8730

How to query nested associations in rails

My models are campaign.rb

has_many: views_logs

user.rb

has_many :views_logs

views_log.rb

belongs_to :campaign
belongs_to :user

I want to get Campaign.first.views_logs.uniq.users.genders I know this query this is wrong but basically I want to get this

Upvotes: 1

Views: 267

Answers (1)

bo-oz
bo-oz

Reputation: 2872

You need to define the direct relationship with the through parameter:

class ModelName
  has_many :views_logs
  has_many :users through: :views_logs
end

Then you can query it like this: model_name.user.where(gender: 'male')

Upvotes: 2

Related Questions