Ruby Gem ActiveRecord find method with multiple conditions

Lior Elrom picture Lior Elrom · Dec 26, 2013 · Viewed 10.7k times · Source

I'm building a Sinatra application using three database's tables: user, post and like.

I'd want to run a query that will find an entry in the like table like so:

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

(for one condition I'll be using: Like.find_by_user_id(params[:user_id]))

My question is:

How to run a find query with multiple conditions using the ActiveRecord Gem?

Answer

falsetru picture falsetru · Dec 26, 2013

Use where:

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

or

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

Is important to keep in mind that the paremeters of the where need to be converted to the expected type for example params[:post_id].to_i