How to fill the select tag with a hash and store the value correctly in the database?

I am trying to set up a form for a model that contains a selection field populated from a collection in a hash.

In particular, my employee model has a hash of roles:

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

And validator:

validates_presence_of :role

Ideally, I would like to fill out a selection box on the form using this information. Sort of:

<%= 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 is not serialized. Instead, I get a verification message that "The role cannot be empty."

My controller creation method is as follows:

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 to populate the selection field with a hash in the model and correctly store the value of the selection field in the column of the employee model in the database?

+3
source share
2

, , ...

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

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

Select_tag [Name, id] (Person.all.collect {| p | [p.name, p.id]})

( , : )

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

:

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

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

:

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

All Articles