Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • Fetching Records in Rails using take

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 370
    Comment on it

    take in Rails:Rails has so many methods that provide the facility to fetching the records from database, so that you don't need to write raw sql. One of them is take.
    By using take we can fetch a record (or N number of records if specified as a parameter) from a table. take doesn't take care of order. The order depends upon the database implementation.

    Example:

    blog = Blog.take
    # => #<Blog id: 1, title: "Active Records in Rails">
    #Sql equivalent is
    SELECT * FROM blogs LIMIT 1
    


    If we want to retrieve n records we can pass it as an argument

    blog = Blog.take(2)
    # => #<Blog id: 1, title: "Active Records in Rails">
    # => #<Blog id: 4, title: "Active Records Validation">
    #Sql equivalent is
    SELECT * FROM blogs LIMIT 2
    


    It can be used with where also:

    blog = Blog.where(title:"Active Records in Rails").take
    

    One similar method is take!. But it returns "ActiveRecord::RecordNotFound" if no record is found.
    Hope you liked reading this for checking find_by. Check this out find_by in Rails

 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: