Ruby on Rails development from scratch (49)-ActiveRecord base (number of rows and reload data)

Source: Internet
Author: User
Tags ruby on rails

The Active record provides two methods to get the number of records that match the criteria: count () and Count_by_sql (). For example:

C1 = order.count
C2 = Order.count (["name =?", "Dave Thomas"])
C3 = Lineitem.count_by_sql ("SELECT COUNT (*)" +
 
   "from Line_items, orders" +
"where line_items.order_id = orders.id" +
"and orders.name = ' Dave Thomas '") 
  puts "Dave has #{c3} line items in #{c2} orders (#{c1} orders in all)"
 

In a program, a database may be accessed by multiple processes or multiple programs, and it is possible to get the latest model objects, which may have just been edited.

In a way, this is mainly used in transactions, anyway, when you need to manually refresh the model object, the Active record can help you, just call the reload () method, the value of the Model object property will be updated by the value in the database.

Stock = Market.find_by_ticker (' RUBY ')
loop do
puts ' price = #{stock.price} ' sleep
stock.reload End
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.