1

Is there anyway to use native database functions in ActiveRecord?

Example: Suppose I want to use now() in Postgres. I don't want to use Time.now because I want the database time to be used, not the Rails server time.

Something like this, which obviously doesn't work.

TableCommon.new( {:upd_date => now()} )

Note: This is a contrived example. I don't want to use now(), but I want to use other database functions, and wish to know how to use it via ActiveRecord.

1 Answer 1

3

Yes, you can access it directly via the connection

TableCommon.new( :upd_date => TableCommon.connection.select_value("now()") )

connection.select_value to get a single result back, ignoring the rest:

   ActiveRecord::Base.connection.select_value("select 1,2")  #returns 1

connection.select to get a hash back:

   ActiveRecord::Base.connection.select("select 1 as a ,2 as b")  #{"a"=>1, "b" =>2}

connection.select_all will give an array of hashes, one per row like select.

connection.select_values will give an array, with the value from the first value in each row. It's like select_value but with multiple rows.

2
  • This would make a db call to get now(), right? Is there anyway to do it without making the db call? Apr 24, 2013 at 19:02
  • It would, otherwise the value wouldn't be available to your model. It's also going to get quoted when the insertion happens. Unless you want to rewrite how rails handles insertions, I would suggest an after_create callback that does something like TableCommon.update_all("dyn_column = now()", :id => self.id) Apr 24, 2013 at 19:16

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.