If any of you want raw sql query in rails you have to use the find_by_sql method. This method returns an array of records. For example
Post.find_by_sql("SELECT title FROM posts WHERE author = ? AND created > ?", author_id, start_date)
will return an array of instantiated objects of Post table.
# => [ #<Post id: 1, title: "Make in India" >, #<Post id: 2, title: "Indian Navy" >, # ...]
select_all is another method like find_by_sql method. This method will retrieve objects from the database using custom SQL just like find_by_sql but will not instantiate them. It will return an array of hashes where each will represent a record of the database. For example
User.connection.select_all("SELECT first_name, created_at FROM users WHERE id = '1'")
will return an array of hashes where each hash indicates a record.
# => [{"first_name"=>"Rafael", "created_at"=>"2012-11-10 23:23:45.281189"},{"first_name"=>"Eileen", "created_at"=>"2013-12-09 11:22:35.221282"}]
0 Comment(s)