ArgumentError ('1' is not a valid type) in Rails
Asked Answered
R

1

6

I am working on a form that has a select list:

<%= f.select :type, options_for_select(Property.types), {prompt: "Select Type of Property..."}, class: "form-control" %>

type is an integer in my database. The Property.types is pulling the list from an enum attribute in my Property model:

enum type: { Type_1: 1, Type_2: 2, Type_3: 3 }

For some reason, when submitting the form, I am getting an error:

ArgumentError ('1' is not a valid type): Completed 500 Internal Server Error in 10ms (ActiveRecord: 4.0ms)

I assume that is because the selected list value is being submitted as a string instead of an integer.

I am using Rails v.5.2.1.

How to solve that issue?

Racketeer answered 15/9, 2018 at 9:57 Comment(2)
Please review the trace and include the relevant portion. Ruby on Rails is great about showing you the file, line and character position which raised the error.Interlace
Try changing the select like this <%= f.select :type, Property.types.map { |key, value| [key.humanize, key] }, {prompt: "Select Type of Property..."}, class: "form-control" %>Marcela
M
9

ArgumentError ('1' is not a valid type)

You should change the select like below

<%= f.select :type, options_for_select(Property.types.map { |key, value| [key.humanize, key] }), {prompt: "Select Type of Property..."}, class: "form-control" %>

Because, this

<%= f.select :type, options_for_select(Property.types), {prompt: "Select Type of Property..."}, class: "form-control" %>

generates the select with options like

<option value="0">Type_1</option>
<option value="1">Type_2</option>
<option value="2">Type_1</option>

So, upon form submit the values of select are sent as "0", "1", "2" which are not valid types for the enum type.

And this

<%= f.select :type, options_for_select(Property.types.map { |key, value| [key.humanize, key] }), {prompt: "Select Type of Property..."}, class: "form-control" %>

generates the select with options like

<option value="Type_1">Type 1</option>
<option value="Type_2">Type 2</option>
<option value="Type_3">Type 3</option>

So now the values of select are sent as "Type_1", "Type_2", "Type_3" which are valid types for the enum type.

Moreover, type is a reserve word(which is used in STI). I recommend changing it to something like property_type

Marcela answered 15/9, 2018 at 10:43 Comment(1)
It worked. Thanks a lot. Also thanks for the tip on changing the column to "property_type".Racketeer

© 2022 - 2024 — McMap. All rights reserved.