Ruby on Rails adding double quotes to “find” function
-
01-06-2021 - |
Question
I'm new to ruby on rails, and I'm having an issue with the find function.
I created a new web app which connects to a legacy Oracle database using the oracle enhanced adapter gem.
When I run the following commands in the rails console, I get data back from the database
License.where(license_no: 'L1234')
or
License.find_by_license_no('L1234')
However, when I try to used the find() function, I get an error. i.e.
License.find(:all)
or
License.all
The error output in the rails console is as follows:
irb(main):003:0> License.find(:all)
?[1m?[35mLicense Load (1062.5ms)?[0m SELECT "LICENSE".* FROM "LICENSE"
ActiveRecord::StatementInvalid: OCIError: ORA-01878: specified field not found i
n datetime or interval: SELECT "LICENSE".* FROM "LICENSE"
from stmt.c:289:in oci8lib_191.so
from c:/RailsInstaller/Ruby1.9.2/lib/ruby/gems/1.9.1/gems/activerecord-o
racle_enhanced-adapter-1.4.1/lib/active_record/connection_adapters/oracle_enhanc
ed_oci_connection.rb:155:in `fetch'
from c:/RailsInstaller/Ruby1.9.2/lib/ruby/gems/1.9.1/gems/activerecord-o
racle_enhanced-adapter-1.4.1/lib/active_record/connection_adapters/oracle_enhanc
ed_adapter.rb:637:in `block in exec_query'
from c:/RailsInstaller/Ruby1.9.2/lib/ruby/gems/1.9.1/gems/activerecord-3
.2.2/lib/active_record/connection_adapters/abstract_adapter.rb:280:in `block in
log'
Looking at the SQL command within the error output, I noticed that double quotes are being added to the select statement. When I tried running the SQL command in SQL Developer, I got an error. Is there any reason why the double quotes are being added? Is there a way to stop ruby on rails from adding the double quotes to the table names?
UPDATE The oracle database is 10g and I'm using rails 3.2 with ruby 1.9.2p290. I've also tried the following and got the same error.
License.all
Solution
The correct formatting for using the find function (depending on what version of Rails you're using) in Rails 3, is:
License.where('license_no = ?', 'L1234')
or
License.all
to find all of them.
If you are in Rails 2, the formatting would be:
License.find(:all, :conditions => ["license_no = ?", "L1234"])
Look at the Dynamic Attribute-Based Finders section here:
OTHER TIPS
Model.find
doesn't accept hash as a first parameter. So it treats your hash (license_no: 'L1234'
) in a wrong way.
http://api.rubyonrails.org/classes/ActiveRecord/FinderMethods.html#method-i-find