Query finder is a methodology where the user finds information from the database by use of SQL queries. The developer uses standard SQL Queries in multiple form and executes them using the find_by_sql method. find_by_sql provides you with a simple way of making custom calls to the database and retrieving instantiated objects.
The find_by_sql method will return an array of objects even if the underlying query returns just a single record.
Examples :
Retrieving complete information:
@loggedinusers = User.find_by_sql(“select * from users where loggedin=true;”)
Retrieving complete information with unknown inputs:
@loggedinusers =User.find_by_sql(["select * from users where loggedin=? and isActive=?",@isloggedin,@isactive]
Retrieving partial information as required:
@loggedinusers = User.find_by_sql(["SELECT username, lastloggedindate, isActive FROM users"])
find_by_sql has a close relative called connection#select_all. select_all will retrieve objects from the database using custom SQL just like find_by_sql but will not instantiate them. Instead, you will get an array of hashes where each hash indicates a record.
Client.connection.select_all("SELECT * FROM clients WHERE id = '1'")
The find_by_sql method will return an array of objects even if the underlying query returns just a single record.
Examples :
Retrieving complete information:
@loggedinusers = User.find_by_sql(“select * from users where loggedin=true;”)
Retrieving complete information with unknown inputs:
@loggedinusers =User.find_by_sql(["select * from users where loggedin=? and isActive=?",@isloggedin,@isactive]
Retrieving partial information as required:
@loggedinusers = User.find_by_sql(["SELECT username, lastloggedindate, isActive FROM users"])
find_by_sql has a close relative called connection#select_all. select_all will retrieve objects from the database using custom SQL just like find_by_sql but will not instantiate them. Instead, you will get an array of hashes where each hash indicates a record.
Client.connection.select_all("SELECT * FROM clients WHERE id = '1'")
No comments:
Post a Comment