Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 750
Johnny Avatar asked Sep 15 '18 09:09

Johnny


1 Answers

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

like image 195
Pavan Avatar answered Sep 24 '22 22:09

Pavan