简体   繁体   中英

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?

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 %>

更简洁:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM