![]() |
Ruby on Rails is Model-View-Controller web-application framework. Rails uses
ActiveRecord database abstraction classes to work with SQL tables. However, sometimes it is more
convenient to work with plain SQL queries(without any model classes) for specific database operations.
Active Record class ActiveRecord::Base has method called connection() which returns valid connection to MySQL (or some other) database using config/database.yml database settings. Return value of connection() method is an object of class MysqlAdpater (or [some-other-database]Adapter). Here are some useful methods of that object:
You can view source of *Adpater classes in /usr/local/lib/ruby/gems/1.8/gems/activerecord-1.14.4/lib/active_record/connection_adaptersfolder, where /usr/local/lib/ruby - is your ruby library folder(may be different). Note, that version numbers (1.8, 1.14.4) likely will also be different. Example: Imagine, you have table with following structure: source code: SQL / MySQL CREATE TABLE `sometable` ( `id` int(11) NOT NULL AUTO_INCREMENT, `value` longtext NOT NULL, `used` tinyint(4) NOT NULL, PRIMARY KEY (`id`), KEY `used` (`used`) ) ENGINE=InnoDB;
Here is the function fetch_value, which will do the task using plain SQL queries: source code: Ruby on Rails def fetch_value sql = ActiveRecord::Base.connection(); sql.execute "SET autocommit=0"; sql.begin_db_transaction id, value = sql.execute("SELECT id, value FROM sometable WHERE used=0 LIMIT 1 FOR UPDATE").fetch_row; sql.update "UPDATE sometable SET used=1 WHERE id=#{id}"; sql.commit_db_transaction value; end
|
|