【发布时间】: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
我想将两个范围条件与一个包含的 or 结合起来。
我尝试过:scope :myscope, lambda { |u| where(cond1: u.id) or where(cond2: u.id)},但它不起作用。我能做什么?
【问题讨论】:
标签: ruby-on-rails ruby activerecord scope conditional-statements
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 方式”的陷阱。
【讨论】:
你可以这样做:-
scope :myscope, lambda { |u| where('cond1 = ? OR cond2 = ?', u.id, u.id)}
【讨论】:
Rails 5 将按照@jphager2 的回答实现“OR”,但同时你必须弄脏你的手:
scope :myscope, lambda {where ["cond1 = ? OR cond2 = ?", u.id, u.id]}
【讨论】:
有一个查询方法#or可以这样使用:
where(cond1: u.id).or(cond2: u.id)
【讨论】: