【问题标题】:How to use a model scope on a .joins query如何在 .joins 查询中使用模型范围
【发布时间】:2014-01-30 05:06:07
【问题描述】:

我有 2 个模型 - User 和 User_detail。

表格:

User
|id|

User_detail
|id|user_id|active|

UserDetails 模型:

class UserDetails < ActiveRecord::Base
    belongs_to :user

    scope :active, -> { where("active is null or active = true") }
end

如何在查询中使用此范围来仅获取活动用户?

类似这样的:

 User.joins(:user_details).active

【问题讨论】:

    标签: ruby-on-rails ruby ruby-on-rails-3 activerecord


    【解决方案1】:

    这似乎有效:

    User.joins(:user_details).merge(UserDetails.active)

    参考:Ruby / Rails - Can I use a joined table's scope(or class method) as part of my WHERE clause?

    【讨论】:

      【解决方案2】:

      这应该可行:

      User.joins(:user_details).merge(UserDetails.active)
      

      查看http://asciicasts.com/episodes/215-advanced-queries-in-rails-3 了解更多 ActiveRecord 技巧!

      【讨论】:

      • 看起来它产生了 2 个单独的查询:User Load (0.8ms) SELECT users.* FROM users INNER JOIN user_details ON user_details.user_id = users.id UserDetails Load (0.4ms) SELECT user_details.* FROM user_details WHERE (active is null or active = true)
      • 看起来&amp; 快​​捷方式已被删除。 merge 仍然有效!
      猜你喜欢
      • 1970-01-01
      • 2017-11-16
      • 1970-01-01
      • 1970-01-01
      • 2017-12-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-08-29
      相关资源
      最近更新 更多