JoHksi JoHksi - 4 months ago 16
JSON Question

Access enum values in Rails model with integer value

In my Rails application, I have a model called

Form
. In
From
model, there is a enum
enum form_type: [:formA, :formB, :formC]
.

I have a json file called
form.json
which has seed data for different types of forms. I basically need to call corresponding seed data for different types of form correctly.

{
"formA" : "seed data1",
"formB" : "seed data2",
"formC" : "seed data3",
}


Let's say I retrieve this json data in a variable called
json_data
. And I create
Form
model in a following way.

I create the
Form
models like below way.:

new_form = Form.create(form_type: params[:form_type], form_data: __ ] )


Using
params[:form_type]
, I need to get string value of
form_type
from the enum. However, if I do
Form.form_types
, I get
{"formA" => 0, "formB" => 1, "formC" => 2}
instead of
[:formA, :formB, :formC]
. Thus, it makes me really hard to get the string type of
form_type
. How can I retrieve
form_type
from the enum using the integer value?

Answer

if Form.form_types gives you {"formA" => 0, "formB" => 1, "formC" => 2} then Form.form_types.keys will give you ["formA", "formB", "formC"]