Sure, use has-many-through:
class A < ActiveRecord::Base
has_many :bs
has_many :cs, :through => :bs
has_many :ds, :through => :cs
end
class B < ActiveRecord::Base
belongs_to :a
has_many :cs
end
class C < ActiveRecord::Base
belongs_to :b
has_many :ds
end
class D < ActiveRecord::Base
belongs_to :c
end
Now you can get all of the ds
for an a
(filtered by status of each d
) by calling:
a.ds.where(status: 1)
And you can call exist?
or any of the query API calls as you would on any ActiveRelation object. Note that all of this assumes that you are trying to work on ds
related to a single a
record. If you are working on a collection of a
records (such as a scoped ActiveRelation), you'll need to take a slightly different approach in getting the result - let me know if this is something you require.