Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • Hash Conditions in Active Records (Rails)

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 721
    Comment on it

    Hash Conditions in Active Records (Rails)

    Active records allows us to to pass in array conditions to our query to fetch a single record or all the records matching 

    the key value pair. In these hash conditions we pass the key as the name of the column through which we have to 

    retrieve the specific records and in the value we pass in the string which we have to match in that particular column.

    • Equality Conditions

    Say for example we have to find all the users who live in Denmark then are hash condition will look like this

    @users = User.where(country:"Denmark")

    or it can also be written as 

    @users = User.where('country'=>'Denmark')

    Here the key is country and value is Denmark.

    • Range Conditions

    In range conditions we set the range in the query according to which we have to fetch the record.

    Say for example we have to fetch the discounted sale from the database which is applicable on today then our 

    query will look like this

    @discounted_sale = DiscountedSale.find_by("start_date <= ? and end_date >= ?", Date.today, Date.today)
    • Subset Conditions

    Now If we want to fetch the records using the IN expression, then we can pass an array to the conditions hash

    @users = User.where(orders_count: [2,4,6])

    so the query at back end will be generated like this

    SELECT * FROM users WHERE (users.orders_count IN (2,4,6))

    So this is how we can use hash conditions to retrieve specific records from table in active records. 

 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: