Reputation: 3308
Ok,
This creates a select box in rails.
<%= select("dashboard_sub_category", "id",options_for_select( @vendor_sub_categories.collect {|p| [p.category_name, p.sub_category_id] }.unshift(["All Categories", 0]))) %>
When my page loads, I want an element in the select box that says,
"All Categories"
and I want it to be selected by default.
I have used unshift like above.
Upvotes: 0
Views: 714
Reputation: 2849
Try adding the include blank to your select code, then in your database set the default position to 0 or All Categories so that when accessing the select menu the default value is 0/All categories.
{:include_blank => 'All Categories'}
Note sure if zI put it inside the correct parenthesis but try this
<%= select("dashboard_sub_category", "id",options_for_select( @vendor_sub_categories.collect {|p| [p.category_name, p.sub_category_id] }.unshift(["All Categories", 0], { :include_blank => 'All Categories' }))) %>
Upvotes: 1
Reputation: 3308
Dude, Your point is, move that operation to the controller, dont do it in the view. I totally agree with that and Im so thankful for your answer.
I will move that to the controller and create @options, thanks.
Now, lets talk about what I disagree with.
Are you saying?
This,
@options = Model.all.inject(Array.new) do |sel, model|
sel << [model.category_name, model.sub_category_id]
end
@options = [["All Categories", 0]] + @options
is better than this,
Model.collect {|p| [p.category_name, p.sub_category_id] }.unshift(["All Categories", 0])
ruby-1.9.2-p290 :027 > timing = Benchmark.measure {@options = v.sub_categories.inject(Array.new) do |sel, model|
ruby-1.9.2-p290 :028 > sel << [model.category_name, model.sub_category_id]
ruby-1.9.2-p290 :029?> end
ruby-1.9.2-p290 :030?> @options = [["All Categories", 0]] + @options
ruby-1.9.2-p290 :031?> }
=> 0.000000 0.000000 0.000000 ( 0.000079)
ruby-1.9.2-p290 :023 > timing = Benchmark.measure { v.sub_categories.collect {|p| [p.category_name, p.sub_category_id] }.unshift(["All Categories", 0])}
=> 0.000000 0.000000 0.000000 ( 0.000086)
Upvotes: 0
Reputation: 11647
Personally, I like to extract the creation of the selector options out in to maybe a before_filter, just so that the view doesn't have to do any of that code. It can just take in something like @options
and in the future you can change how that's generated without changing the view, just the controller, as that falls under its scope. The view shouldn't do any real coding work.
Then I usually generate that like this:
@options = Model.all.inject(Array.new) do |sel, model|
sel << [model.category_name, model.sub_category_id]
end
@options = [["All Categories", 0]] + @options
Then you can just use @options
for your select tag.
Upvotes: 1