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

时间:2022-12-13 21:46:27

I can't figure out the correct way to write this where statement for my controller in one line.

我找不出正确的方法把控制器的where语句写成一行。

What am I missing here?

我错过了什么?

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

Here is my attempt to write it in 3 lines.

我试着用三行来写。

@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 correctly displays the objects like this. Why wont it let me do something like this now?

@food_rank正确地显示了这样的对象。为什么现在不让我做这样的事呢?

 @food_rank each do |rank|
   rank.user_id
 end

Is it making @food_ranks literally the where statement? (undefined method)

它是否使@food_rank成为where语句?(未定义的方法)

2 个解决方案

#1


5  

Try this way:

试试这种方法:

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

You can also do:

你也可以做的事:

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

#2


1  

The problem is you are passing in an array, and trying to compare rank to that.

问题是你传入一个数组,并试图比较它的秩。

Try changing it like so:

试着这样改变:

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

Rails will automatically generate the SQL IN statement from the array, so no need to specify that.

Rails将自动从数组中生成SQL IN语句,因此不需要指定它。

#1


5  

Try this way:

试试这种方法:

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

You can also do:

你也可以做的事:

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

#2


1  

The problem is you are passing in an array, and trying to compare rank to that.

问题是你传入一个数组,并试图比较它的秩。

Try changing it like so:

试着这样改变:

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

Rails will automatically generate the SQL IN statement from the array, so no need to specify that.

Rails将自动从数组中生成SQL IN语句,因此不需要指定它。