Active Record Find by OR Column Rails

Is it possible to execute a find_by query using the 'or' operator? For instance:

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

Something like (doesn't work):

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

Thanks!

+4
source share
5 answers

Do not use Activerecord methods

This might work:

 code = params[:code] @product = Product.find(:all, :conditions => ["upc = ? or cspc = ?", code, code]) 
+9
source

Clearing Nicholas code:

 @products = Product.all(:conditions => ["upc = :code or cspc = :code", {:code => params[:code]}]) 
+4
source

As far as I know, Rails does not support automatic OR crawlers out of the box. But the searchlogic stone seems to support this feature. See here

+1
source

I had a similar problem as before.

One way to get close to this is to try to figure out what type of data you get first. Write a code that will tell you the difference.

Maybe see if there is a regular expression method for distinguishing between UPC and CSPC.

+1
source

If you use Arel in Rails 3:

 t = Product.arel_table @products = Product.where( t[:upc].eq(params[:code]) \ .or(t[:cspc].eq(params[:code])) ) @product = @products.first if @products.size == 1 
+1
source

All Articles