- vừa được xem lúc

Know count, size, and length to save on SQL queries in Ruby on Rails

0 0 3

Người đăng: Viet

Theo Viblo Asia

It’s important to know the differences between these three methods to ensure you’re triggering the fewest or most optimized SQL queries possible.

The count method always triggers a SELECT count(*) FROM table query. The length method ensures that the relationship has been loaded to count in memory. The size method adapts to the loading of the relationship. Either it triggers a query if it hasn't been loaded, or it counts in memory if it has already been loaded.

Here's a summary table:

Records Loaded Record Not Loaded
count SELECT count(*) FROM table SELECT count(*) FROM table
size Count in memory SELECT count(*) FROM table
length Count in memory SELECT * FROM table

When counting and enumerating, it’s important to call size after the relationship has been loaded. In all cases, the aim is to trigger a single request.


# Bad 2 queries instead of 1
users = User.all
users.size # SELECT count(*) FROM "users"
users.each {} # SELECT "users".* FROM "users" # Good
users = User.all
users.length # SELECT "users".* FROM "users"
users.each { } # No queries # Good
users = User.all
users.each { } # SELECT "users".* FROM "users"
users.size # No queries # Good
users = User.all.load # SELECT "users".* FROM "users"
users.size # No queries
users.each { } # No queries # Bad 2 queries instead of 1
users = User.all
users.each { } # SELECT "users".* FROM "users"
users.count # SELECT COUNT(*) FROM "users"

Bình luận

Bài viết tương tự

- vừa được xem lúc

Tôi cá là bạn không biết những điều này - Ruby on rails ( Phần 2)

Các bạn có thể theo dõi phần 1 ở đây :. https://viblo.asia/p/toi-ca-la-ban-khong-biet-nhung-dieu-nay-ruby-on-rails-phan-1-WAyK8DDeKxX. 5.

0 0 211

- vừa được xem lúc

Rails Memoization

Memoization is a process that can be used to speed up rails methods. It caches the results of methods that do time-consuming work, work that only needs to be done once. Here is an example. Example.

0 0 34

- vừa được xem lúc

Tại sao Rails lại dùng cả Webpack lẫn Sprocket?

Khi Rails 6 được ra mắt, có thể bạn đã từng tự hỏi. WTF, sao Webpack đã được add vào rồi, mà Sprocket vẫn tồn tại thế kia . Chẳng phải Webpack và Sprocket được dùng để giải quyết chung một công việc hay sao. Hoặc cả đây:.

0 0 47

- vừa được xem lúc

Bạn nên sử dụng Elasticsearch trong ứng dụng Ruby On Rails như thế nào?

Elasticsearch là một công cụ phân tích và mã nguồn mở mạnh mẽ và linh hoạt, phân tán, theo thời gian thực. Đó là tiêu chuẩn vàng trong công nghệ tìm kiếm.

0 0 70

- vừa được xem lúc

Form object pattern trong rails

1.Mở đầu.

0 0 100

- vừa được xem lúc

Sử dụng Twilio để gửi SMS trong ứng dụng Ruby on Rails

Ngoài cách xác nhận tài khoản hay gửi thông báo bằng email thì hôm nay mình sẽ hướng dẫn các bạn 1 cách nữa là thông qua SMS/Voice. Công cụ sử dụng sẽ là gem Twilio. Installation. Để cài đặt bằng Bundler, hãy lấy phiên bản mới nhất:.

0 0 56