Rails Snippets — Arbitrary SQL

On February 26, 2009, in Development, Ruby and Rails, by tov

Seems I’m in a Ruby/Rails mood today

Sometimes you don’t need the whole Rails stuff and just want to place a query.

Try the following:

ActiveRecord::Base.connection.(select_all|update)

will do the trick.
Example:


list = ActiveRecord::Base.connection.select_all("select a,b from c_table")

–>

[ {a => Value_for_a, b => Value_for_b}, {a => Value...}...]

number_of_rows = ActiveRecord::Base.connection.update("update month set month_id = month_id +1 where month_id = 11")

If you make use of an already created Rails Model instead of the base class, you will get the benefit of accessors (instead of hash-keys) for the  selected objects.

Example (necessary, I know :-) )

  • create the model

# script/generate model CTable

  • use it in your code

list = CTable.find_by_sql("select a,b from c_table")

  • access elements

pp list[0].a