Rails 5:ActiveRecord使用OR条件

时间:2017-04-28 09:49:53

标签: ruby-on-rails ruby-on-rails-5 ruby-on-rails-5.1

我需要一些帮助来查询(Rails 5.1)。我有一个名为Verificationbelongs_to :verifiable, polymorphic: true)的多态关联对象。其他对象(例如Comment)可以verificationshas_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]

我该怎么办?

1 个答案:

答案 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"]]