3

我正在尝试为模型设置一个表单,该表单包含从哈希中的集合填充的选择框。

具体来说,我的员工模型有一个角色散列:

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

和一个验证器:

validates_presence_of :role

理想情况下,我想使用此信息在表单中填充选择框。例如:

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

虽然我可以在选择框中显示值,但数据没有序列化。相反,我收到“角色不能为空”的验证消息。

我的控制器的创建方法如下所示:

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

最终,我的问题是如何使用模型中的哈希填充选择框并将选择框的值正确保存到数据库中员工模型的列中?

4

2 回答 2

8

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 %>
于 2011-05-20T01:00:24.293 回答
0

更简洁:

<%= f.select :role, Employee::ROLES.invert %>
于 2017-01-26T19:24:50.827 回答