我正在处理具有选择列表的表单:
<%= f.select :type, options_for_select(Property.types), {prompt: "Select Type of Property..."}, class: "form-control" %>
type
是我的数据库中的一个整数。 Property.types
从我的Property模型中的enum
属性中拉出列表:
enum type: { Type_1: 1, Type_2: 2, Type_3: 3 }
出于某种原因,在提交表单时,我收到一个错误:
ArgumentError('1'不是有效类型):10ms内完成500内部服务器错误(ActiveRecord:4.0ms)
我假设这是因为所选列表值是作为字符串而不是整数提交的。
我正在使用Rails v.5.2.1。
如何解决这个问题?
ArgumentError('1'不是有效类型)
你应该像下面这样改变select
<%= f.select :type, options_for_select(Property.types.map { |key, value| [key.humanize, key] }), {prompt: "Select Type of Property..."}, class: "form-control" %>
因为这
<%= f.select :type, options_for_select(Property.types), {prompt: "Select Type of Property..."}, class: "form-control" %>
用select
生成options
<option value="0">Type_1</option>
<option value="1">Type_2</option>
<option value="2">Type_1</option>
因此,在表单提交时,select
的值将作为"0", "1", "2"
发送,这不是enum type
的有效类型。
还有这个
<%= f.select :type, options_for_select(Property.types.map { |key, value| [key.humanize, key] }), {prompt: "Select Type of Property..."}, class: "form-control" %>
用select
生成options
<option value="Type_1">Type 1</option>
<option value="Type_2">Type 2</option>
<option value="Type_3">Type 3</option>
所以现在select
的值被发送为"Type_1", "Type_2", "Type_3"
,它们是enum type
的有效类型。
此外,qazxsw poi是一个保留字(用于STI)。我建议把它换成类似qazxsw poi的东西