views:

45

answers:

5

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!

+3  A: 

Not using Activerecord methods

This might work:

code = params[:code]
@product = Product.find(:all, :conditions => ["where upc = ? or cspc = ?", code, code])
nicholasklick
Thanks Nicholas! Exactly what I was looking for.
Kevin Sylvestre
+1  A: 

As far as I know Rails doesn't support automatic OR finders, out of the box. But the searchlogic gem appears to support this feature. See here

bjg
Yeah, that was what I thought. I took a look at the search-logic gem and have used it in the past. Thanks for the reply.
Kevin Sylvestre
+1  A: 

I've had a similar problem like this before.

One way to approach it is to try and figure out what type of data you're getting in the first place. Write some code that will tell you the difference.

Maybe see if there is a regex way to distinguish between UPC and CSPC.

Good point. I could take a look at adding a length check (the UPC-A codes are all 12 characters, and CSPC are 6 or 7 I believe). Thanks.
Kevin Sylvestre
+1  A: 

Cleaning up nicholas' code:

@products = Product.all(:conditions => ["upc = :code or cspc = :code", {:code => params[:code]}])
Omar Qureshi
Thanks Omar for the nice refractor. I ended up doing this to clean up the code a bit.
Kevin Sylvestre
+1  A: 

If you're using Arel on 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
Dan McNevin