我有这样的多对多关系:
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)
但它返回此错误:
ActionView::Template::Error (SQLite3::SQLException: no such column: letter_trackings.assignees: SELECT "letter_trackings".* FROM "letter_trackings" WHERE "letter_trackings"."assignees" IN (1189)):
那是因为我不知道如何在 arel 中查询关联的(多对多)列。
有什么想法吗?
您需要
获取用于创建 HABTM 关联的连接表,并搜索assignee_id或user_id以查询信件跟踪中的被分派者。您可以参考以下代码片段。我假设连接表是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)