Tom
Tom

Reputation: 15940

How do I populate a select tag with a hash and properly save the value to the database?

I'm attempting to setup a form for a model that contains a select box populated from a collection in the hash.

Specifically, my employee model has a hash of roles:

ROLES = {1 => "Lead", 2 => "Engineer", 3 => "Intern" }

And a validator:

validates_presence_of :role

Ideally, I'd like to populate a select box in a form using this information. Something such as :

<%= form_for @employee do |f| %>
    <%= label_tag :role, "Role" %>
    <%= f.select :employee, :role, Employee::ROLES %>
<% end %>

Although I can display the values in the select box, the data isn't serialized. Instead, I receive the validation message that the "Role can't be blank."

My controller's create method looks like this:

def create
  @employee = Employee.new(params[:employee])
  if @employee.save
    redirect_to employees_path, :notice => "Successfully created a new employee."
  else
    render :action => 'new'
  end
end

Ultimately, my question is how do I populate the select box using the hash in the model and properly save the value of the select box to the column on the employee model in the database?

Upvotes: 3

Views: 6276

Answers (2)

stevenspiel
stevenspiel

Reputation: 5999

More succinctly:

<%= f.select :role, Employee::ROLES.invert %>

Upvotes: 0

Jesse Wolgamott
Jesse Wolgamott

Reputation: 40277

It'll be easier if you follow the advice and use an array to store your Roles, but you don't have to... We can just convert it into an array at render time

ROLES = {1 => "Lead", 2 => "Engineer", 3 => "Intern" }

puts ROLES.map{|r| [ r[0], r[1] ]}
=> [[1, "Lead"], [2, "Engineer"], [3, "Intern"]]

The select_tag expects an array of [Name,id] (Person.all.collect {|p| [ p.name, p.id ] })

(Note that you don't want :employee here)

<%= f.select :role, Employee::ROLES.map{|role| [ role[1], role[0] ]} %>

If you don't want to both with this:

ROLES = ["Lead", "Engineer", "Intern"]

<%= f.select :role, Employee::ROLES %>

Upvotes: 8

Related Questions