【发布时间】:2021-07-15 09:29:31
【问题描述】:
快速提问。 我正在尝试建立一个没有成功的范围。我有这些模型
class User < ActiveRecord::Base
belongs_to :store, required: true
has_many :visits
has_one :company, through: :store
end
class Store < ActiveRecord::Base
belongs_to :company, required: true
has_many :users, dependent: :nullify
end
class Company < ActiveRecord::Base
has_many :stores, dependent: :destroy
has_many :users, through: :stores
end
class Visit < ActiveRecord::Base
belongs_to :user
end
编辑
现在我需要使用 Chartkick Gem 绘制一些图表,最好的方法是从 Visit 模型开始。
我正在使用
Visit.group_by_day("started_at", range: 3.month.ago.midnight..Date.today.midnight, format: "%b %-e").order("day asc").count
如果我需要所有访问,但现在我还需要过滤公司和商店的访问。
我不明白如何才能获得属于特定商店或特定公司的用户的所有访问。
最简单的方法是:
Visit.where("user_id IN (?)", company.users.ids)
它有效,但我不想写一个更好的范围,而我写的那个不起作用。
class Visit < ActiveRecord::Base
belongs_to :user
scope :user_by_store, ->(store_id) {
joins(:user).where('user.store_id' => store_id)
}
end
【问题讨论】:
标签: ruby-on-rails activerecord