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!
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.
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.
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.
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])
Not using Activerecord methods
This might work:
code = params[:code]
@product = Product.find(:all, :conditions => ["upc = ? or cspc = ?", code, code])
Cleaning up nicholas' code:
@products = Product.all(:conditions => ["upc = :code or cspc = :code", {:code => params[:code]}])
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With