Hey again guys,
I did come up with a problem few weeks ago and I still don’t have an
elegant solution for it. I’d like to hear your opinions on how to deal
with it, since it’s rather basic and could be quite common.
Imagine a view showing peoples clothing.
Stefan’s hat: stefan.cloths.find_by_location “head”
Stefan’s shirt: stefan.cloths.find_by_location “shirt”
Stefan’s jeans: stefan.cloths.find_by_location “jeans”
Stefan’s left_glove: stefan.cloths.find_by_location “left_glove”
Stefan’s right_glove: stefan.cloths.find_by_location “right_glove”
etc…
quite a few queries. bad performance. the thing is though, before
reaching the view the association has been already initialized. so, the
rows already exist in the action, and they are retrieved again
one-by-one in the view.
to avoid retrieving them again, i build a hash in the action this way:
for cloth in cloths; @cached_clothes[cloth.location] = cloth; end
and in the view:
Stefan’s hat: @cached_clothes[“head”]
It “works”. But does not seem elegant. an other approach i tried:
Stefan’s hat: stefan.clothes.select{|c| c.location == “head”}.first
Doesnt seem to be the correct “rails way” either.
Is there a “rails way” for doing this?
Thank you
Stefan