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.
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.
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)
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)