【问题标题】:Ruby on Rails ActionController: scope combined with inclusive orRuby on Rails ActionController:范围与包容性或
【发布时间】:2016-03-01 16:31:21
【问题描述】:

我想将两个范围条件与一个包含的 or 结合起来。

我尝试过:scope :myscope, lambda { |u| where(cond1: u.id) or where(cond2: u.id)},但它不起作用。我能做什么?

【问题讨论】:

    标签: ruby-on-rails ruby activerecord scope conditional-statements


    【解决方案1】:

    ActiveRecord 提供了一些方法来绕过编写 SQL 的需要,但在这种情况下,您需要付出很少的努力并编写一小段 SQL。

    scope :myscope, -> { |u| where("cond1 = ? OR cond2 = ?", u.id, u.id) }
    

    你也可以更简洁用起来

    scope :myscope, -> { |u| where("cond1 = :id OR cond2 = :id", id: u.id) }
    

    写一些SQL没有错。不要落入“如果我不能用 Ruby 编写它,不管它是否丑陋,或者不是 Rails 方式”的陷阱。

    【讨论】:

      【解决方案2】:

      你可以这样做:-

      scope :myscope, lambda { |u| where('cond1 = ? OR cond2 = ?', u.id, u.id)}
      

      【讨论】:

        【解决方案3】:

        Rails 5 将按照@jphager2 的回答实现“OR”,但同时你必须弄脏你的手:

        scope :myscope, lambda {where ["cond1 = ? OR cond2 = ?", u.id, u.id]}
        

        【讨论】:

        • 不脏,就是叫SQL,没什么毛病。 ;)
        【解决方案4】:

        有一个查询方法#or可以这样使用:

        where(cond1: u.id).or(cond2: u.id)
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2014-05-11
          • 2015-08-30
          • 2011-01-24
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多