Ruby Gem ActiveRecord find method with multiple conditions

10,921

Solution 1

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

Solution 2

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

Solution 3

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

Solution 4

If you are expecting one record 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 record that you expect to match your search.

If you are expecting more than one record to be the result:

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

Share:
10,921

Related videos on Youtube

Lior Elrom
Author by

Lior Elrom

I'm a software engineer who like to learn and explore new technologies and not afraid to ask questions when needed.

Updated on August 22, 2022

Comments

  • Lior Elrom
    Lior Elrom over 1 year

    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?