How expensive is using select boxes with a model and what is best pracitce?
assuming I have a Model A and a Model B.
class A < ActiveRecord::Base
has_one :b
end
class B < ActiveRecord::Base
end
开发者_开发技巧And a form for A where all possible B's are listed for choosing.
...
<div class="field">
<%= f.label :hv_type_id %><br />
<%= f.collection_select :b_id, @bs, :id, :name %>
</div>
...
I did
@bs = B.all
in the controller method of A.
Is this best practice? What if A holds another assosiaction for e.g: C
Should the the controller of A load all C's as well? What is your expierience, do thinks like this slow down the application a lot? Is there a way to handle this efficiently? See http://en.wikibooks.org/wiki/Ruby_on_Rails/ActionView/Forms#Using_select_boxes_with_a_modelAlthough your code as written will not work (e.g. you have two "Class A", you use @bs in your controller but bs in your view - which are different variables, etc.), I get your drift. The answer is based on the number of records that you are retrieving for the select box.
If it's just a few, then there is no problem. If you are displaying hundreds or thousands of choices, that is definitely a problem, on multiple levels: it will create a huge page for the user to download, eating up a ton of bandwidth; and it will make their job of trying to find and select a record very difficult.
If you have to associate with many records in this way, you would be better off using an auto-complete. Or, build the application so you start by choosing a sub-record before going to the form. E.g. step one would be to retrieve a "B" by using, say, a search, and step 2 would be adding additional information that is associated with B.
精彩评论