[Rails Tips] Rails 7.1 – ActiveRecord::QueryMethods#select has added support for hash values

Trong bản cập nhật mới nhất của, Rails 7.1 đã cho phép chúng ta query select theo giá trị hash chứ không cần phải sử dụng raw SQL nữa.

💎 Improvements:
1️⃣ New support query với giá trị Hash
2️⃣ Chúng ta không cần phải dùng truy vấn raw version nữa

💎 Bonus:
1️⃣ Cú pháp mới cũng support chúng ta sử dụng alias
2️⃣ Sử dụng tương tự cho ActiveRecord#reselect

Ruby
# Before Rails 7.1

Post.joins(:comments)
    .select(
      "posts.id as post_id, posts.title as post_title,
      comments.id as comment_id, comments.body as comment_body"
    )
    
Post.joins(:comments).select(:id, :title, "comments.body")

# After Rails 7.1

Post.joins(:comments)
    .select(
      posts: { id: :post_id, title: :post_title },
      comments: { id: :comments_id, body: :comment_body }
    )
    
Post.joins(:comments).select(:id, :title, comments: [:body] )
0 Shares:
6 comments
Leave a Reply

Your email address will not be published. Required fields are marked *

You May Also Like
Cài đặt Rails 7 với Vite + Stimulus + Tailwind
Read More

Cài đặt Rails 7 với Vite + Stimulus + Tailwind

Nếu bạn đang tìm kiếm một giải pháp phát triển web hiệu suất cao và tiện lợi, Vite sẽ là lựa chọn đáng xem xét. Còn với Rails 7, bạn sẽ phải cân nhắc xem tính năng importmap có đủ thuyết phục để bạn chuyển đổi không.
Read More

Setup slack notifications in Rails

Table of Contents Hide Setup Slack:Setup Rails: Slack là một phần mềm Worksplace sử dụng thông dụng rộng…