【问题标题】:Rails scope on association of associationRails 协会协会的范围
【发布时间】: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


    【解决方案1】:

    我认为你应该能够做到:

    scope :by_company, -> (company) { joins(:company).where(companies: {id: company}) }
    

    【讨论】:

      【解决方案2】:

      当您在方法where 中添加“user.store_id”时,您使用的是 SQL。根据 Rails 标准,表的名称通常是复数

      您需要在代码中修复的唯一一件事是更改 user -> users

      scope :user_by_store, ->(store_id) {
        joins(:user).where('users.store_id' => store_id) 
      }
      

      当然,对于按公司进行过滤,您可以使用@oreoluwa 的答案,但要修复表格名称中的相同错误。

      scope :by_company, -> (company) { joins(:company).where(companies: {id: company}) }
      

      【讨论】:

        猜你喜欢
        • 2015-10-16
        • 1970-01-01
        • 1970-01-01
        • 2012-01-20
        • 2015-01-06
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多