I have 4 models, A, B, C and D
class A < ActiveRecord::Base
has_many :B
has_many :C, :through => :B
end
class B < ActiveRecord::Base
belongs_to :A
has_many :C
has_many :D, :through => :C
end
class C < ActiveRecord::Base
belongs_to :B
end
class D < ActiveRecord::Base
belongs_to :C
end
I have a very naive implementation which is very obvious …
<% A.B.each do |b| %>
<%= b.number %>
<% b.C.each do |c| %>
<%= c.name %>
<% end %>
<% end %>
What’s the best way to get All C for A?
What’s the best way get All D for A?
I want to get all ‘C’ using order_by clause with “created_at” value instead of iterating through B.
May be I’m missing some ActiveRecord magic?
I appreciate any help.
First of all, you need to make a couple changes.
class Cneeds an association toDIf you want to access
A‘sD‘s, you need to specify this as well.Now, to access all of
A‘sC‘s:Notice how another query is not executed when you call
a.C. This is because ActiveRecord knows you will want to access the foundA‘sC‘s by theincludecall, and generates the minimum number of queries. Same goes forD‘s:Say you wanted all
A‘sD‘s but wantedC‘s ordered:Note you can also set this as a default on the association: