Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Active Record Find By Column 'OR' Rails

Is it possible to perform a find_by query using an 'or' statement? For example:

@product ||= Product.find_by_upc(params[:code]) if params[:code]
@product ||= Product.find_by_cspc(params[:code]) if params[:code]

As something like (does not work):

@product ||= Product.find_by_upc_or_cspc(params[:code]) if params[:code]

Thanks!

like image 404
Kevin Sylvestre Avatar asked Jul 26 '10 20:07

Kevin Sylvestre


People also ask

Can you use ActiveRecord without Rails?

One of the primary aspects of ActiveRecord is that there is very little to no configuration needed. It follow convention over configuration. ActiveRecord is commonly used with the Ruby-on-Rails framework but you can use it with Sinatra or without any web framework if desired.

What is ActiveRecord relation in Rails?

The Relation Class. Having queries return an ActiveRecord::Relation object allows us to chain queries together and this Relation class is at the heart of the new query syntax. Let's take a look at this class by searching through the ActiveRecord source code for a file called relation.

Is ActiveRecord an ORM?

ActiveRecord is an ORM. It's a layer of Ruby code that runs between your database and your logic code. When you need to make changes to the database, you'll write Ruby code, and then run "migrations" which makes the actual changes to the database.


3 Answers

As of Rails 5, one way to do this is as follows:

For the first matching record:

Product.find_by("upc = ? OR cspc = ?", params[:code], params[:code])

For all matching records:

Product.where("upc = ? OR cspc = ?", params[:code], params[:code])
like image 122
jayqui Avatar answered Oct 16 '22 19:10

jayqui


Not using Activerecord methods

This might work:

code = params[:code]
@product = Product.find(:all, :conditions => ["upc = ? or cspc = ?", code, code])
like image 9
nicholasklick Avatar answered Oct 16 '22 19:10

nicholasklick


Cleaning up nicholas' code:

@products = Product.all(:conditions => ["upc = :code or cspc = :code", {:code => params[:code]}])
like image 6
Omar Qureshi Avatar answered Oct 16 '22 17:10

Omar Qureshi