Đang chuẩn bị nút TẢI XUỐNG, xin hãy chờ
Tải xuống
Và, không, không phải là một hình thức find_by_ cho phép bạn sử dụng _or_ hơn là _and_ giữa tên cột. Tải lại dữ liệu Trong một ứng dụng cơ sở dữ liệu có khả năng bị truy cập bởi nhiều quy trình (hoặc nhiều ứng dụng), luôn luôn có khả năng rằng một đối tượng mô hình lấy đã trở thành cũ, một người nào đó có thể đã viết một bản sao để cơ sở dữ liệu. | Callbacks 266 J Joe Asks. If . Why Are ofterjind and after_initialize Special Rails has to use reflection to determine if there are callbacks to be invoked. When doing real database operations the cost of doing this is normally not significant compared to the database overhead. However a single database select statement could return hundreds of rows and both callbacks would have to be invoked for each. This slows things down significantly. The Rails team decided that performance trumps consistency in this case. There are two basic ways of implementing callbacks. First you can define the callback instance method directly. If you want to handle the before save event for example you could write class Order ActiveRecord Base . . def before_save self.payment_due Time.now 30.days end end The second basic way to define a callback is to declare handlers. A handler can be either a method or a block.3 You associate a handler with a particular event using class methods named after the event. To associate a method declare it as private or protected and specify its name as a symbol to the handler declaration. To specify a block simply add it after the declaration. This block receives the model object as a parameter. class Order ActiveRecord Base before_validation normalize_credit_card_number after_create do order logger.info Order order.id created end protected def normalize_credit_card_number self.cc_number.gsub - w end end You can specify multiple handlers for the same callback. They will generally be invoked in the order they are specified unless a handler returns 3A handler can also be a string containing code to be eval ed but this is deprecated. Report erratum Callbacks 267 false and it must be the actual value false in which case the callback chain is broken early. Because of a performance optimization the only way to define callbacks for the after_find and after_initialize events is to define them as methods. If you try declaring them as handlers using the second .