Ruby Gem ActiveRecord finds a method with multiple conditions

I am creating a Sinatra application using three database tables: user , post and like .

I want to run a query that finds an entry in a like table, for example:

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

(for one condition I will use: Like.find_by_user_id(params[:user_id]) )

My question is:

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

+7
ruby ruby-on-rails activerecord gem sinatra-activerecord
source share
4 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) 

It is important to remember that parameters of parameters where you need to convert to the expected type, for example, params[:post_id].to_i

+9
source share

Similar to the user_id column for user_id , you can combine multiple column names to get the dynamic find_by_user_id_and_post_id :

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

If there are more than β€œtolerant” columns in the search for find_by_ , you can use where and set the condition as follows:

 Like.where(user_id: params[:user_id], post_id: params[:post_id]) 
+3
source share

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

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

 Like.where("user_id = ? AND post_id = ?", params[:user_id], params[:post_id]) 
+2
source share

If you expect one entry to be the result:

To replace find_by_whatever , you can use find_by(whatever) , for example User.find_by(username:"UsernameIsMyUsername",password:"Mypassword") . You should use find_by if there is only one entry that you expect from your search.

If you expect the result to be more than one entry:

If you expect more than one, you should use where with where(username:"MyUsername",password:"Password") . This will return all resulting records in the array.

0
source share

All Articles