我需要一些帮助来查询(Rails 5.1)。我有一个名为Verification
(belongs_to :verifiable, polymorphic: true
)的多态关联对象。其他对象(例如Comment
)可以verifications
(has_many :verifications, as: :verifiable
),最后一个(按id
排序)被视为当前对象。 Verification
具有枚举属性status
。我需要检索具有特定user_id
(当前用户之一)或当前(即最后)验证对象且具有正确状态的评论(例如,approved
)
所以,我正在尝试:
self.where(user_id: user.id).or(self.joins(:verifications).limit(1).where(verifications: { status: 'approved' }))
但是Rails给了我以下错误:
Relation passed to #or must be structurally compatible. Incompatible values: [:joins, :references, :limit]
我该怎么办?
答案 0 :(得分:1)
我无法在一个查询中使其工作(My Arel尝试失败)。所以希望以下就足够了(测试工作):
latest_verification_ids = Verification.group(:verifiable_id).maximum(:id).values
# SELECT MAX("verifications"."id") AS maximum_id, "verifications"."verifiable_id" AS verifications_verifiable_id FROM "verifications" GROUP BY "verifications"."verifiable_id"
comments_whose_user_id_is_user_id_or_whose_last_verification_is_approved =
Comment
.where(user_id: user_id)
.or(
Comment.where(id:
Comment.joins(:verifications)
.where(
verifications: {
id: latest_verification_ids,
status: 'approved'
}
)
)
)
# SELECT "comments".* FROM "comments" WHERE ("comments"."user_id" = ? OR "comments"."id" IN (SELECT "comments"."id" FROM "comments" INNER JOIN "verifications" ON "verifications"."verifiable_id" = "comments"."id" AND "verifications"."verifiable_type" = ? WHERE "verifications"."id" IN (4, 2) AND "verifications"."status" = ?)) [["user_id", 1], ["verifiable_type", "Comment"], ["status", "approved"]]