Question

I've dropdown with US states with the full name of each state and a hidden value as the abbreviation. When a user saves the hidden value (abbreviation) is stored in the database and we return it in the "show" action.

I could create a helper method, but I've few more dropdowns with similar problem that's why looking for an easier solution.

I've also tried readonly and disabled but both of these render the HTML control as well which is not required:

profiles_helper.rb
def us_states
[     
  ['Alabama', 'AL'],
  ['Alaska', 'AK'],
  ['Arizona', 'AZ']     
]
end

I am using simple form:

_form.html.erb
<%= simple_form_for(@profile) do |f| %>
    <%= f.input :state, collection: us_states %>
<% end %>

What should I do in show.html.erb to display the full name of each state instead of the abbreviation. Is there anything available in simple form?

show.html.erb
<%= @profile.state %>
Was it helpful?

Solution 2

I've fixed this problem by creating another helper method. "get_value" method will take collection and hidden value of the field and return the visible value. Collection is first converted into a Hash and then passing the hidden value to index operator returns visible value. Following is the code for us_states similarly any collection can be passed to this method to get visible value:

profiles_helper.rb
def us_states
[     
  ['Alabama', 'AL'],
  ['Alaska', 'AK'],
  ['Arizona', 'AZ']     
]
end

def get_value(collection, hidden_value)
    hash = Hash[collection.map {|key, value| [value, key]}]
    hash[hidden_value]
end

_form.html.erb
<%= simple_form_for(@profile) do |f| %>
    <%= f.input :state, collection: us_states %>
<% end %>

show.html.erb
<%= get_value(us_states, @profile.state %>

OTHER TIPS

Define a method in your Profile model to bring the State full name.

def state_name
  state = State.where("id= #{self.state}").first
  state.name
end

In your show you will only have to call such method to display the state's full name:

<%= @profile.state_name %>
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top