Can anyone please tell me what’s going on here, I’ve copied something
pretty much directly from rails guides, but it’s just not doing what
it’s supposed to!
(Or I’m doing something stupid!)
rails - 3.2.2
ruby 1.9.3
my view has the following
1 - <% formations_array = @formations.map { |f| [f, f] } %>
2 - <%= formations_array.each do |f| f.to_s end%>
3 - <%= f.select(:formation_csv, options_for_select(formations_array,
2)) %>
-
the array of arrays is created from the @formations
-
prints this array of arrays [[“4-3-3”, “4-3-3”], [“5-3-2”, “5-3-2”],
[“4-4-2”, “4-4-2”]]
(as I expect)
-
creates the select box, and hard coded asks for index 2 to be
currently selected, as on rails docs here : <%=
options_for_select([[‘Lisbon’, 1], [‘Madrid’, 2], …], 2) %>
However when I look at the page, the wrong selection is selected, always
index 0, not index 2.
Can anyone please tell me what’s going on here! Or is this a bug?
Thanks,
Michael
On 10 May 2012 11:45, Michael B. [email protected] wrote:
1 - <% formations_array = @formations.map { |f| [f, f] } %>
2 - <%= formations_array.each do |f| f.to_s end%>
3 - <%= f.select(:formation_csv, options_for_select(formations_array,
2)) %>
You are using f.select, rather than select_tag. This doesn’t require
options_for_select. It will select the :formation_csv from the form’s
model.
I don’t know what your model is, but let’s say it’s Team.
In your controller:
@team = Team.new
@team.formation_csv = “5-3-2”
In your view:
<%= form_for @team do |f| %>
<%= f.select(:number, formations_array) %>
<% end %>
That will select 5-3-2. If you load the model from the db, it will use
the
saved value automatically.
Also, I don’t think you need line 1. If you pass an array of values,
Rails
will use them for both text and value, so line 1 is redundant.
Does that all make sense?
Thanks for that, it works exactly as you said! cheers, now I have the
line
<%= f.select(:formation_csv, @formations) %>
and it magically knows which one to select.
I’m still v curios as to why the “options_for_select(formations_array,
2)” didn’t do anything, is it because when I’m using this in conjunction
with the form_helper, ie f.select as opposed to select_tag, the
options_for_select method becomes redundant, or different?
On 10 May 2012 12:13, Michael B. [email protected] wrote:
options_for_select method becomes redundant, or different?
Yeah, it’s redundant. Your code was also wrong The second paramater
needs to be the value of the selected object, not the array index. So
options_for_select(formations_array, “5-3-2”) would probably have
worked.
It’s a bad idea though in a resource-based form though.
Glad you’ve got it sorted! My experience with Rails says if something
feels
like it’s getting unnecessarily complex, you’re probably doing it wrong!