Tutorial :Where to put code that generates select options



Question:

I have a select dropdown where I generate the options from database entries, then add an option to the beginning like:

@select = Service.find_services_by_id(id).collect { |p| [p.name, p.id] }  @select.unshift( [ "Choose a service", 0] )  

Then in the HAML view I have:

=select_tag "service_id", options_for_select(@select)  

But I'm looking at refactoring that either by:

1) Adding another method to the model which also does the unshift operation to return to me all the data for the select in one piece

2) Moving the whole @select definition to a view helper and calling it from the view

3) Just have that first @select line in the controller, then have a view helper do the 'unshift' part

But I'm having trouble figuring out what makes the most sense. Thoughts?


Solution:1

I'd go for 3rd, but not only do the unshift in the helper, but create whole select thingie there too:

module SomeHelper    def service_select(objects)      select_tag "service_id", options_for_select(objects.unshift(["Select a service", 0]))    end  end  

Then in view you'd just call =service_select(@select).


Solution:2

1) does not make a lot of sense. The model should not be sticking headers on data to pretty it up - that's the view's job.

2) and 3) are both reasonable - I'm personally leaning towards 3), but either one is good.


Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »