Luke Cramer Luke Cramer - 7 months ago 11
Ruby Question

Correct way to write where statement with array of values

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

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 each do |rank|
rank.user_id
end


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

Answer

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])