Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby Gem ActiveRecord find method with multiple conditions

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?

like image 446
Lior Elrom Avatar asked Dec 26 '13 03:12

Lior Elrom


3 Answers

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

like image 150
falsetru Avatar answered Oct 19 '22 20:10

falsetru


Similar to find_by_user_id for user_id column you can combine multiple column names and get a dynamic finder find_by_user_id_and_post_id:

Like.find_by_user_id_and_post_id(params[:user_id], params[:post_id])

When there are more than "bearable" columns in the find_by_ finder, you could use where and supply the condition as follows:

Like.where(user_id: params[:user_id], post_id: params[:post_id])
like image 5
vee Avatar answered Oct 19 '22 20:10

vee


Like.find_by_user_id(params[:user_id]) - this syntax is deprecated in ActiveRecord 4.

Instead try using where method of ActiveRecord query interface, to pass array conditions. Example:

Like.where("user_id = ? AND post_id = ?", params[:user_id], params[:post_id])
like image 2
Srikanth Venugopalan Avatar answered Oct 19 '22 19:10

Srikanth Venugopalan