如何查询 rails 中的嵌套关​​联

How to query nested associations in rails

我的模特是 campaign.rb

has_many: views_logs

user.rb

has_many :views_logs

views_log.rb

belongs_to :campaign
belongs_to :user

我想得到Campaign.first.views_logs.uniq.users.genders 我知道这个查询是错误的,但基本上我想得到这个

你需要定义与through参数的直接关系:

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

然后可以这样查询:model_name.user.where(性别:'male')