Rails范围包含2个where子句

时间:2013-05-01 16:48:07

标签: ruby-on-rails

我有一个rails scope语句,我想要2 where子句。 (当我工作时,我会清理硬编码。)

这是在我的工作订单模型中:

  scope :laborok, where("wostatus_id NOT IN (?)", [231, 230, 8466, 8467, 232] ) and where("maxsynch = (?)", "N" )

逻辑是,如果工作订单状态(wostatus.id)不是值,并且workorder.maxsynch等于“N”

3 个答案:

答案 0 :(得分:3)

你可以链接where()方法:

scope :laborok, where("wostatus_id NOT IN (?)", [1]).where("maxsynch = (?)", "N")

注意,我用[1]替换了您的ID数组! 以下是包含ID数组的代码:

scope :laborok, where("wostatus_id NOT IN (?)", [231, 230, 8466, 8467, 232]).
                  where("maxsynch = (?)", "N")

答案 1 :(得分:1)

为什么要链接?

class Workorder < ActiveRecord::Base
    scope :laborok, lambda do |ids, maxsynch| 
        where("wostatus_id NOT IN (?) AND maxsynch = ?", ids, maxsynch)
    end
end

答案 2 :(得分:0)

将放入字符串的内容简单地传递给您的数据库适配器,并将参数的值替换为。因此,最简单的形式是仅使用AND关键字:

scope :laborok, where(["wostatus_id NOT IN (?) AND maxsynch = (?)", [231, 230, 8466, 8467, 232], "N"] )

?字符串中有多个where,第一个参数是传递给数据库适配器的字符串,后续参数按照提供的顺序替换为字符串。

如果链接在特定情况下更具可读性,那么链接也可以正常工作:

scope :laborok, where("wostatus_id NOT IN (?)", [231, 230, 8466, 8467, 232]).
                where("maxsynch = (?)", "N")

许多ActiveRecord Query Interface methods都可以这种方式链接。