Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • Retrieving a Single Object From Active Records In Rails

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 138
    Comment on it

    Active records gives us different ways to retrieve single objects from it.

    Those methods with examples are given below : 

    • find

    The find method allows us to retrieve a single object or we can say single record from the database by passing in the record ID in the method. 

    user = User.find(10)

    This will find get the record from the user table whose ID is 10.

    The same method can be used to get multiple objects as well. All we need to do is pass in an array of all the primary keys whose records we need to get.

    users = User.find([2,8,9,15])

    This will get us all the users who have primary keys as stated in the array.

     

    • first

    The first method allows us to retrieve the first record from the table on which it is being run.

    user = User.first

    This will get us the first user from the user table.

    The same method can also be used to get first n number of records from the table.

    user = User.first(6)

    This will get us the first 6 users from the user table.

     

    • take

    The take method will fetch us any record without any specific ordering.

    user = User.take(4)

    This will give us any four records from the users table without any specific order.

     

    • last

    The last method allows us to retrieve the last record from the table on which it is being run.

    user = User.last

    This will get us the last user from the user table.

    The same method can also be used to get last n number of records from the table.

    user = User.last(6)

    This will get us the last 6 users from the user table.

     

    • find_by

    This method allows us to fetch a record from the table through any column name of that table.

    user = User.find_by(name:"Tom",city:"Los Angles")

    This will get the users who names is Tom and their city is Los Angles.

 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: