使用 arel 查询关联字段(多对多关系)

query for associated fields (many to many realtion) with arel

我有这样的多对多关系:

class User < ApplicationRecord
    has_and_belongs_to_many :letter_trackings
end

class LetterTracking < ApplicationRecord
    has_and_belongs_to_many :assignees, class_name: "User"
end

我想像这样使用 arel 搜索受让人 :

users = User.arel_table
letter_trackings = LetterTracking.arel_table

@users = User.where(users[:name].matches("%#{Afsane Fadaei}%"))
@assignees_ids = @users.pluck(:id).uniq
letters_query = letter_trackings[:assignees].in(@assignees_ids)
@letter_trackings = LetterTracking.where(letters_query)

但是 returns 这个错误:

ActionView::Template::Error (SQLite3::SQLException: no such column: letter_trackings.assignees: SELECT "letter_trackings".* FROM "letter_trackings" WHERE "letter_trackings"."assignees" IN (1189)):

那是因为我不知道如何在arel.

中查询associated(多对多)列

有什么想法吗?

您需要抓取用于创建 HABTM 关联的连接 table 并搜索 assignee_id 或 user_id 以在信件跟踪中查询受让人。您可以参考以下代码片段。我假设加入 table 是 LetterTrackingUsers。

letter_trackings = LetterTracking.arel_table
letter_trackings_users = LetterTrackingUsers.arel_table # here use HABTM table used by you for joining users and letter_trackings

query = letter_trackings_users[:user_id].in(@assignees_ids)  
or 
query = letter_trackings_users[:assignee_id].in(@assignees_ids)

@letter_trackings = LetterTracking.where(letters_query)