Я попытался настроить рабочие модели, которые должны соответствовать тому, чего вы пытаетесь достичь, и вот результат:
class A
include DataMapper::Resource
property :id, Serial
has n, :bs
has n, :cs, :through => :bs, :via => :c
def active_cs
cs.active
end
end
class B
include DataMapper::Resource
property :id, Serial
belongs_to :a
belongs_to :c
end
class C
include DataMapper::Resource
property :id, Serial
property :end_on, Date
property :applied_to, Date
has n, :bs
def active
all(:end_on => nil) + all(:conditions => [ "cs.end_on > applied_to" ])
end
end
a = A.create
b = B.create(:a => a)
c = C.create(:b => b)
puts a.active_cs.inspect
Вот запрос SQL:
SELECT "id", "end_on", "applied_to" FROM "cs" WHERE ("id" IN (SELECT "cs"."id" FROM "cs" INNER JOIN "bs" ON "cs"."id" = "bs"."c_id" INNER JOIN "as" ON "bs"."a_id" = "as"."id" WHERE ("bs"."a_id" = 1 AND "cs"."end_on" IS NULL)) OR "id" IN (SELECT "cs"."id" FROM "cs" INNER JOIN "bs" ON "cs"."id" = "bs"."c_id" INNER JOIN "as" ON "bs"."a_id" = "as"."id" WHERE ("bs"."a_id" = 1 AND (cs.end_on > applied_to)))) GROUP BY "id", "end_on", "applied_to" ORDER BY "id"
Я не уверен, что это именно то, что вам нужно, но я надеюсь, что это поможет.
Вот ссылка на гист с рабочим скриптом: https://gist.github.com/916164