Given 2 quan hệ ActiveRecord tạo ra sau SQL:Làm thế nào để hợp nhất (link) 2 Quan hệ trên các bảng khác nhau trong Rails 4
- quan
a = SELECT comments.* FROM comments INNER JOIN attachments ON attachments.comment_id = comments.id WHERE attachment.name ILIKE '%foo%
- quan
b = SELECT attachments.* FROM attachments INNER JOIN users ON attachments.user_id = users.id WHERE users.other_conditions
này làm việc trong Rails/ActiveRecord :
puts a.merge(b).to_sql # Rails 3
> "SELECT comments.* FROM comments INNER JOIN attachments ON attachments.comment_id = comments.id INNER JOIN users ON attachments.user_id = users.id WHERE attachment.name ILIKE '%foo% AND users.other_conditions"
Tôi nghĩ rằng nó hoạt động vì merge
đã bỏ qua mọi liên kết không tồn tại trên các truy vấn.
Nhưng Rails là nhiều hơn nữa pedantic và không thành công với:
puts a.merge(b).to_sql # Rails 4
> ActiveRecord::ConfigurationError: Association named 'user' was not found on Comment; perhaps you misspelled it?
Vì vậy, câu hỏi là làm thế nào tôi có thể theo nghĩa đen hợp nhất 2 quan hệ mà không Rails là lo lắng về tính chính xác (thông số kỹ thuật của tôi chịu trách nhiệm về điều đó)?
Kiểm tra đá quý Arel được sử dụng trong nội bộ của Rails - https://github.com/rails/arel và một số ví dụ/thông số kỹ thuật tại đây https://github.com/rails/arel/tree/master/test bạn có thể nhận được một số thông tin chi tiết hơn. –
@OtoBrglez không thể tìm thấy bất kỳ con trỏ nào ở đó. Bạn có gì không? –