theDrifter theDrifter - 3 months ago 15
JSON Question

ActiveRecord Connection Adapter return value

I had a bit more complex sql-query which i decided to use plain

sql
rather than writing it with AR. I wrapped the sql-statement inside ActiveRecord::Base.connection.exec_query` .

The method basically looks like that:

def sc_agent
return ActiveRecord::Base.connection.exec_query("SQL").as_json
end


The serializer
as_json
gives me a json hash with json strings. So also id's are now strings

{"id":"123","age":"99"}


On standard queries where i use AR i receive nicely
formatted json with the correct types.

How can i retain the correct types of all the values when using the ConnectionAdapter directly? Thanks for everything!

Answer

Use find_by_sql method.

Example: Post.find_by_sql ["SELECT title FROM posts WHERE author = ? AND created > ?", author_id, start_date].

More info is here: http://api.rubyonrails.org/classes/ActiveRecord/Querying.html