Pregunta

I have models A,B,C,D. A model has multiple records of B, B of C and C of D.

I wanted to know if there is any way that I can go from A to D with a cleaner way than going from A to B... recursivly to D, making a huge and heavy code.

I was wondering if its possible to write something like

aa = A.something
if aa.bs.cs.ds.where(:status=>1).any?
 ...

I don't know how to title this better so maybe misleading...

¿Fue útil?

Solución

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.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top