Drew
Drew

Reputation: 2631

Rails - find by with two fields using OR instead of AND?

I am familiar with doing a find on two fields:

user = User.find_by_username_and_email(params[:username], params[:email])

However, I would like to retrieve one record where the username OR email equals the same field. Something like:

user = User.find_by_username_or_email(params[:text])

Which I know doesn't work. Is this possible? Any help is a appreciated.

Upvotes: 3

Views: 2832

Answers (2)

Matt
Matt

Reputation: 14038

Just to expand on the answer by @xdazz, you can use the following syntax to allow searching any number of fields by the same value without having to repeat the value:

user = User.where('username = :text or email = :text', :text => params[:text]).first

Very useful when you come to search postal address fields, for example.

2.2.1 Placeholder Conditions

Upvotes: 8

xdazz
xdazz

Reputation: 160883

You could use .where :

user = User.where('username = ? or email = ?', params[:text], params[:text]).first

Upvotes: 7

Related Questions