TAILIEUCHUNG - Ruby for Rails phần 7

Đoạn mã sau định nghĩa một class tên là Person. Bên cạnh phương thức 'initialize', là hàm tạo dùng để tạo ra đối tượng mới, nó có 2 phương thức khác: một là override toán tử so sánh (vì thế Array#sort có thể sắp xếp theo tuổi) và cái còn lại là override phương thức to_s (vì thế Kernel#puts có thể định dạng dữ liệu ra của nó). | Using arrays 291 The code starts by grabbing a Work object and getting from it the full list of its editions B. The editions collection reports its class as Array C. However the collection of editions refuses to accept a string as an element When you try to push a string onto the collection you get a fatal error D. This is a good illustration of the fact that a Ruby object in this case a collection of editions isn t constrained to behave exactly the way a default or vanilla instance of its class would behave. For Ruby objects including objects that house other objects being created is just the beginning. What matters is how the object gets shaped and used down the road. ActiveRecord collections consider themselves instances of Array but they have special knowledge and behaviors that differentiate them from arrays in general. This is a great example of the Ruby philosophy bearing fruit with practical results. Searching and filtering ActiveRecord-style ActiveRecord s approach to finding elements in collections is also instructive. At a general level you can perform find operations on the entire existing set of records for any model you ve defined. Here s an example all Sonata You re operating at the class and class method level You re looking for all existing objects corresponding to database records under the hood of the given class. A couple of points are noteworthy here. First ActiveRecord uses find all rather than find_all. Actually either will work but find_all is considered old-style usage and is likely to disappear from future versions of ActiveRecord. Second note the call to the method find_by_title. That method is created automatically because instances of Work have title attributes. This is another example of the Rails framework giving you a good return on your investment In return for creating a database field called title you get a method that lets you search specifically on that field. find all and its close relative find .

Đã phát hiện trình chặn quảng cáo AdBlock
Trang web này phụ thuộc vào doanh thu từ số lần hiển thị quảng cáo để tồn tại. Vui lòng tắt trình chặn quảng cáo của bạn hoặc tạm dừng tính năng chặn quảng cáo cho trang web này.