更新:
感谢@TomLord 的洞察力,您宁愿执行下面的解决方案 1 而不是解决方案 2。另外,添加示例 SQL 以显示比较。
解决方案 1
class Team < ApplicationRecord
belongs_to :hunt
scope :ready, -> { joins(:hunt).where(hunts: { confirmed: true }) }
end
用法:
Team.ready # or: Team.all.ready
# SELECT "teams".* FROM "teams" INNER JOIN "hunts" ON "hunts"."id" = "teams"."hunt_id" WHERE "hunts"."confirmed" = ? LIMIT ? [["confirmed", "t"], ["LIMIT", 11]]
或者,解决方案 2
class Team < ApplicationRecord
belongs_to :hunt
end
class Hunt < ApplicationRecord
scope :confirmed, -> { where(confirmed: true) }
end
用法:
# you can also move the logic below as a method/scope inside `Team` model (i.e. as `ready` method/scope)
# Example 1 (using JOINS):
Team.joins(:hunt).where(hunts: { id: Hunt.confirmed })
# SELECT "teams".* FROM "teams" INNER JOIN "hunts" ON "hunts"."id" = "teams"."hunt_id" WHERE "hunts"."id" IN (SELECT "hunts"."id" FROM "hunts" WHERE "hunts"."confirmed" = ?) LIMIT ? [["confirmed", "t"], ["LIMIT", 11]]
# Example 2 (same as Example 1 above but faster and more efficient):
Team.where(hunt_id: Hunt.confirmed)
# SELECT "teams".* FROM "teams" WHERE "teams"."hunt_id" IN (SELECT "hunts"."id" FROM "hunts" WHERE "hunts"."confirmed" = ?) LIMIT ? [["confirmed", "t"], ["LIMIT", 11]]