使用值数组编写 where 语句的正确方法

Correct way to write where statement with array of values

我想不出在一行中为我的控制器编写此 where 语句的正确方法。

我在这里错过了什么?

@food_ranks = FoodRank.where("user_id = ? AND rank = ?", current_user.id, [0, 1, 2])

这是我尝试用 3 行写的。

@food_ranks = Array.new(FoodRank.where("user_id = #{current_user.id} AND rank = 0"))
@food_ranks << FoodRank.where("user_id = #{current_user.id} AND rank = 1")
@food_ranks << FoodRank.where("user_id = #{current_user.id} AND rank = 2")

@food_ranks 正确显示这样的对象。为什么它现在不让我做这样的事情了?

 @food_rank each do |rank|
   rank.user_id
 end

它是否使 @food_ranks 字面意思是 where 语句? (未定义的方法)

试试这个方法:

@food_ranks = FoodRank.where("user_id = ? AND rank IN (?)", current_user.id, [0, 1, 2])

您还可以这样做:

@food_ranks = FoodRank.where(user_id: current_user.id, rank: [0, 1, 2])

问题是您正在传递一个数组,并试图将排名与该数组进行比较。

试试这样改:

FoodRank.where("user_id = ?", current_user.id, rank: [0, 1, 2])

Rails 会自动从数组中生成 SQL IN 语句,所以不需要指定。