Free, tested & ready to use examples!
AnyExample.com
 
Web anyexample.com
 


AnyFormat.io - convert files and webpages to any format!

Rails and SQL queries

abstract 
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.
compatible 
  • Ruby On Rails 0.14 or higher
  • 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:

    • execute - executes SQL query. For "SELECT ..." query will return Mysql::Result class (or other result-set class for your Ruby database interface).
    • insert - executes SQL query and returns last inserted id
    • update, delete - executes SQL query and returns number of affected rows
    • begin_db_transaction - executes SQL query 'BEGIN' (transaction start)
    • commit_db_transaction - executes SQL query 'COMMIT' (confirm transaction)
    • rollback_db_transaction - executes SQL query 'ROLLBACK' (rollback transaction)
    There is also methods select_all and select_one, but we do not recommend using it, because of inefficient implementation trying to fetch all selected values to memory.

    You can view source of *Adpater classes in

     
    /usr/local/lib/ruby/gems/1.8/gems/activerecord-1.14.4/lib/active_record/connection_adapters
    			
    folder, 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;
     
    • id field - primary key
    • value field (some valuable data)
    • used flag (contains boolean 0 or 1)
    Imagine, you need to write transaction-safe code, which will fetch any 'unused'(used=0) field, return its value and mark is as 'used'(used = 1). For MySQL you have to use "SELECT ... FOR UPDATE" to ensure that nothing else will fetch the same row simultaneously with your application.

    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				
     
    warning 
  • Ruby On Rails is MVC framework. Direct SQL usage may be considered as an application design flow, from MVC architecture point of view
  • tested 
  • FreeBSD 6.0 :: Ruby On Rails 1.1.6
  •  


     
    © AnyExample 2010-2013
    License | Privacy | Contact