Ruby-on-rails Rails 4 语法 - 多个条件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19638294/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 22:57:51  来源:igfitidea点击:

Rails 4 Syntax - Multiple Conditions

ruby-on-rails

提问by Katie M

How would I write this correctly?

我该如何正确地写这个?

Request.pending.where(.....)  ## Request.pending = request.state_id in (1..3)

where these are the conditions:

这些是条件:

approver1_id = current_user and state_id = 1
or
approver2_id = current_user and state_id = 2
or
approver3_id = current_user and state_id = 3

It would be really nice if I could put these conditions in the model for use in other controllers/views, too, because I will use these conditions quite often throughout the app.

如果我也可以将这些条件放在模型中以用于其他控制器/视图,那就太好了,因为我将在整个应用程序中经常使用这些条件。

回答by AWM

Try:

尝试:

Request.pending.where(
  '(approver1_id= ? AND state_id= ?) OR
   (approver2_id= ? AND state_id= ?) OR
   (approver3_id= ? AND state_id= ?)',
  current_user.id,
  1,
  current_user.id,
  2,
  current_user.id,
  3
)

Edit: I forgot that you should use colons. And shouldn't it be 'current_user.id'? It is also unclear whether your Request use the three parameters approver1_id - approver3_id or just one approver_id per request.

编辑:我忘了你应该使用冒号。不应该是'current_user.id'吗?还不清楚您的请求是使用三个参数批准人 1_id - 批准人 3_id 还是每个请求只使用一个批准人 ID。

Edit 2: Changed query to SQL.

编辑 2:将查询更改为 SQL。

回答by exbinary

To answer the second part of your question about reusing this query, you can just define a class method on Requestthat accepts a user parameter:

要回答有关重用此查询的问题的第二部分,您只需定义一个Request接受用户参数的类方法:

# usage: Request.pending_approval(current_user)
def self.pending_approval(user)
  pending.where("(approver1_id = :user AND state_id = 1) OR 
                 (approver2_id = :user AND state_id = 2) OR 
                 (approver3_id = :user AND state_id = 3)", 
                user: user)
end

If you want to be able to reuse the individual fragments of the query and combine them as needed, see this related answer(Note, the answer linked to is better than the accepted one, IMO).

如果您希望能够重用查询的各个片段并根据需要组合它们,请参阅此相关答案(注意,链接到的答案比公认的 IMO 更好)。

回答by Hare Kumar

Well

First get all the state_id & store it in array. and then pass that array in where clause. It is similar to Mysql INquery.

首先获取所有 state_id 并将其存储在数组中。然后在 where 子句中传递该数组。它类似于 Mysql IN查询。

Hence your query will be something like:

因此,您的查询将类似于:

state_id = [1, 2, 3]  
Request.pending.where(:state_id => state_id AND :approved_id => current_user.id)

I hope it will fetch you the desired result.

我希望它能带给你想要的结果。