Ruby on Rails development from scratch (48)-ActiveRecord Basics (Dynamic query)

Source: Internet
Author: User
Tags ruby on rails

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.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.