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

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 167
    Comment on it

    find method: The find method is used to find the particular object that matches with the parameter supplied to it.

     article = Article.find(11)     #It is used to find the article whose primary key is 11.
     # => #<Article id: 11, name: "Rahul">

              Sql query be like:

     SELECT * FROM articles WHERE (articles.id = 11) LIMIT 1

    This method will raise an ActiveRecord::RecordNotFound exception if it does not find any record in the database.

     

    first method: The first method is used to find the first record that is being ordered by the primary key.

    article = Article.first     #It finds the first article in your database.
    # => #<Article id: 1, name: "first article">

        Sql query be like:

    SELECT * FROM articles ORDER BY articles.id ASC LIMIT 1

    This method does not return any exception , it simply returns nil if no record is found.

     

    find_by method: The find_by method is used to find the first record that matches the conditions applied.

     Article.find_by name: 'first article'
     # => #<Article id: 1, name: "first article">

    Instead of writing like this you can also write like:

    Article.where(name: 'first article')

     

    take method: The take method is used to find a record in which we do not have to pass any order.

    article = Article.take
    # => #<Article id: 1, name: "first article">

    Sql query be like:

    SELECT * FROM articles LIMIT 1

     

    last method: The last method is used to find the last record as defined by the primary key.

    article = Article.last
    # => #<Article id: 122, name: "Virat">

    Sql query be like:

    SELECT * FROM articles ORDER BY articles.id DESC LIMIT 1

 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: