Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • Direct sql Queries in Rails

    • 0
    • 3
    • 2
    • 0
    • 0
    • 0
    • 0
    • 0
    • 349
    Comment on it

    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)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: