Frage

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?

War es hilfreich?

Lösung

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

Andere Tipps

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

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.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top