Ruby Gem ActiveRecord查找具有多个条件的方法

问题描述 投票:11回答:4

我正在使用三个数据库表构建Sinatra应用程序:userpostlike

我想运行一个查询,在like表中找到一个条目,如下所示:

FIND in like WHERE user_id == params[:user_id] AND post_id == params[:post_id]

(对于我将使用的一个条件:Like.find_by_user_id(params[:user_id])

我的问题是:

如何使用ActiveRecord Gem运行具有多个条件的查找查询?

ruby-on-rails ruby activerecord gem sinatra-activerecord
4个回答
11
投票

使用where

Like.where('user_id = ? AND post_id = ?', params[:user_id], params[:post_id])

要么

Like.where('user_id = :user_id AND post_id = :post_id', params)

重要的是要记住,需要转换为预期类型的​​参数,例如qazxsw poi


4
投票

params[:post_id].to_i列的find_by_user_id类似,您可以组合多个列名称并获得动态查找器user_id

find_by_user_id_and_post_id

Like.find_by_user_id_and_post_id(params[:user_id], params[:post_id]) 查找器中有多个“可忍受”列时,您可以使用find_by_并提供如下条件:

where

2
投票

Like.where(user_id: params[:user_id], post_id: params[:post_id]) - 在Like.find_by_user_id(params[:user_id])中不推荐使用此语法。

而是尝试使用ActiveRecord查询接口的ActiveRecord 4方法来传递where。例:

array conditions

1
投票

If you are expecting one record to be the result:

要替换Like.where("user_id = ? AND post_id = ?", params[:user_id], params[:post_id]) ,您可以使用find_by_whatever例如find_by(whatever)。如果只有一条记录与搜索匹配,则应使用User.find_by(username:"UsernameIsMyUsername",password:"Mypassword")

If you are expecting more than one record to be the result:

如果你期望不止一个,你应该使用find_bywhere。这将返回数组中的所有结果记录。

© www.soinside.com 2019 - 2024. All rights reserved.