Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • Array Conditions and selecting specific fields to find or retrieve from database (Active records)

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 72
    Comment on it

    Array Conditions and selecting specific fields to find or retrieve from database through Active records

    Array Conditions

    To retrieve some specific data from the database we use the where method which gets the records in the form of arrays.

    • Now if a situation arises that we have to directly find from the form parameters then we would write a query like this
    User.where("orders_count = ?", params[:orders])

    This will go to the users table and find will retrieve the all the users who have orders till the count specified in the params[:orders] value coming from the form

    • In case of multiple conditions where we want to find with more conditions then we can write like this
    User.where("orders_count = ? AND active = ?", params[:orders], true)

    This will go to the users table and find will retrieve the all the users who have orders till the count specified and all those who have active marked as true.

    Selecting Specific Fields

    Always by default .find method selects all the fields of the model and gives it back to us in the variable.

    But if a condition arises when we need only some specific fields from the model then we can use the select method to do so. Below is the code to achieve it

    User.select("name, age")

 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: