Ruby on rails 使用Rails控制台查询具有条件的多个模型

Ruby on rails 使用Rails控制台查询具有条件的多个模型,ruby-on-rails,Ruby On Rails,我正在尝试使用rails控制台编写我的语句,下面是我的模型之间的关系: class Lead < ApplicationRecord belongs_to :user end class User < ApplicationRecord has_many :leads belongs_to :stores end class Store < ApplicationRecord has_many :users end 以上能够给我从商店id

我正在尝试使用rails控制台编写我的语句,下面是我的模型之间的关系:

class Lead < ApplicationRecord
    belongs_to :user
end

class User < ApplicationRecord
    has_many :leads
    belongs_to :stores
end

class Store < ApplicationRecord
    has_many :users
end
以上能够给我从商店id 1的所有线索。我还了解了如何获取过去7天所有门店的所有潜在客户:

Lead.where(created_at: 7.days.ago..Time.zone.now.end_of_day).count

我想知道如何将这两种方法结合在一起,只显示每个商店最后7天的销售线索(或销售线索数量)。谢谢您

为了简化操作,请使用关联将潜在客户与门店关联起来

class Store < ApplicationRecord
    has_many :users
    has_many :leads, through: :users
end
class Store < ApplicationRecord
    has_many :users
    has_many :leads, through: :users
end
s1 = Store.find(1)
s1.leads.where(created_at: 7.days.ago..Time.zone.now.end_of_day).count