Reputation: 41929
to be honest, I almost find html forms more straightforward than Rails form helpers. I'm trying to turn this text form into a select box with options Canada, United States, Mexico as strings
<p><%= f.label :country %><br />
<%= f.text_field :country %></p>
Because the model is already represented in the block variable "f", I'm not sure how to alter the syntax because the model is usually represented first in the complicated hash of variables and options http://api.rubyonrails.org/classes/ActionView/Helpers/FormOptionsHelper.html#method-i-select
Can anyone show me?
Upvotes: 1
Views: 2951
Reputation: 96934
The following should work:
<%= f.select :country, [["Canada", "Canada"], ["Mexico", "Mexico"], ["United States", "United States"]] %>
You can read more in the Rails Guides & API docs. As @ka8751 says, though, if you have a Country
model, collection_select
makes this far easier:
<%= f.collection_select :country, Country.all, :id, :name %>
where :id
is used for the actual value
of the <option>
tag and :name
is used for what is displayed.
If you don't have a Country
model, you should consider one for the sake of database normalization.
Upvotes: 9
Reputation: 2918
I think you have mistake here: you are using text_field
instead of select
method. To make select box I would recommend you to use collection_select
method:
<%= f.collection_select :country, Country.all, :id, :name %>
Also there is a wonderful gem country_select
to solve your problem and it used by formtastic formtastic which I also recommend you to use for building your forms.
Upvotes: 0