Henley Wing Chiu
Henley Wing Chiu

Reputation: 22515

Can ActiveRecord call native db functions?

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.

Upvotes: 1

Views: 1100

Answers (1)

Shawn Balestracci
Shawn Balestracci

Reputation: 7530

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.

Upvotes: 3

Related Questions