【问题标题】:Chaining multiple scopes with different joins to same table in squeel将具有不同连接的多个范围链接到 squeel 中的同一个表
【发布时间】:2012-10-06 09:04:43
【问题描述】:

这个问题出现在 squeel 1.0.11 上。我已经提交了an issue,但我认为社区可能已经有了答案。

我的模型中同一个表有两个关系,我在两个不同范围的连接中使用这两个关系。

class Log < ActiveRecord::Base
  attr_accessible :created_by_id, :updated_by_id
  belongs_to :created_by, class_name: "User"
  belongs_to :updated_by, class_name: "User"
  scope :suggested,
    joins{created_by}.
    where{(created_by.can_admin_logs == false) | 
          (created_by.can_admin_logs == nil)}
  scope :not_edited,
    joins{updated_by}.
    where{(updated_by.can_admin_logs == false) |
          (updated_by.can_admin_logs == nil)}
end

当这些范围一起改变时,sql是不正确的。

Log.suggested.not_edited.to_sql

SELECT "logs".* FROM "logs" INNER JOIN "users" ON "users"."id" = "logs"."created_by_id" INNER JOIN "users" "updated_bies_logs" ON "updated_bies_logs"."id" = "logs"."updated_by_id" WHERE (("users"."can_admin_logs" = 'f' OR "users"."can_admin_logs" IS NULL)) AND (("updated_bies_logs"."can_admin_logs" = 'f' OR " updated_bies_logs"."can_admin_logs" 为 NULL))

我已经修改了各种更改来解决 updated_bies_logs 问题,但还没有找到解决方案。

1.0.11 的发行说明似乎解决了这个问题,但我更新了我的 gem,问题仍然存在。

【问题讨论】:

    标签: ruby-on-rails squeel


    【解决方案1】:

    除了 jdoe 的回答之外,您可能还希望将作用域包装在 lambdas 中,以避免在加载模型时执行。请注意,在涉及范围内的 lambda 时存在一些问题:http://ryreitsma.blogspot.com.au/2011/07/ruby-on-rails-3-chaining-scopes-with.html

    【讨论】:

      【解决方案2】:

      你制作了一些扭曲的瞄准镜。毫不奇怪,你让你的尖叫声尖叫起来:)

      我会这样写:

      # in User
      scope :cannot_admin_logs, where{can_admin_logs.eq_any [false, nil]}
      
      # in Log 
      scope :suggested,  joins{created_by}.merge(User.cannot_admin_logs)
      scope :not_edited, joins{updated_by}.merge(User.cannot_admin_logs)
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2011-06-15
        • 2015-10-31
        • 2012-06-11
        • 1970-01-01
        • 2018-12-26
        • 2014-08-26
        相关资源
        最近更新 更多