The most frequently run query on a database is to return a conforming result set based on a specified condition, and the query may be to return all the names ' Dave's order, or all the titles on a blog with rails, in many other frameworks and programming languages, you need to create SQL to execute queries, and Active record takes advantage of the dynamic capabilities that the Ruby language contains.
For example, our order model contains attributes such as name,email,address, which we can query by using the Find method corresponding to these names, for example:
Order = Order.find_by_name ("Dave Thomas")
orders = Order.find_all_by_name ("Dave Thomas") Order
= Order.find_ All_by_email (params[' email ')
If you call a model class of Find_by_ or Find_all_by_, the Active record converts them to a query (finder), and the string that follows the method converts the parameters of the Find method to the field name. For example:
Order = Order.find_by_name ("Dave Thomas", the other args ...)
The equivalent of the call above is converted to:
Order = Order.find (: I,
: Conditions => ["name =?", "Dave Thomas"],
Other_args ...)
Similarly, calling a Find_all_by_xxx method is equivalent to calling find (: all, ...) Method.
Here the magic has not stopped, the Active record can also create a query for multiple columns (finder), for example, you can write:
user = User.find_by_name_and_password (name, PW)
Equivalent:
user = User.find (: Before
: Conditions => ["name =?] and password =? ", name, PW])
In order to determine which fields to check, the Active record simply splits the strings behind Find_by_ and Find_all_by_, which is sufficient in most cases, unless you do not have a field in the method name.
Note that the Active record does not provide _or_ in the two field names that follow the Find_by_ or find_all_by.