I have a Ruby on Rails form that takes the input and saves it as model attributes. One of the attributes, though, holds json data. I would like to be able to take the data entered into multiple fields and save it as a single JSON object in my models attribute. Is there a way I could do this?
If it helps, I could also make a Hash and convert it to json. Basically I just want to combine multiple input fields into one, then hand it off from there.
Thanks!
There are multiple things to consider here.
The first problem is to get your data out of the HTML form. If you use the standard Rails way of naming your form inputs, it's quite simple.
<input name="my_fields[value1]">
<input name="my_fields[value2]">
<input name="my_fields[sub1][value1]">
<input name="my_fields[sub1][value2]">
If you name them like that they can be accessed "en bloc" using the params
hash via params[:my_fields]
, which gives you another hash containing your data.
Then you have to choose which way to save this data in your model. There are several options:
1. Use a string attribute
Just use a string
or text
column and assign a JSON string:
@my_model.my_data = params[:my_fields].to_json
2. Use a serialized hash
Use a string
or text
column and declare it as serializable on your model
serialize :my_data, Hash
Then you can use this column as it was a simple hash and Rails will perform the reading and writing operations.
@my_model.my_data = params[:my_fields]
to_json
is necessary if you need a real JSON string.3. Use specialized JSON database types
In case you need to be able to query the database using SQL the solutions above won't work. You have to use specialized types for that.
Many DBMS provide structured datatypes in form of XML or even JSON types. (PostgreSQL for example)
Update: Since Rails 5 JSON column types are supported. If you are using PostgreSQL or MySQL just use t.json
(or t.jsonb
) in your migration and use that attribute like a regular hash.
You can save all multiple files as text in JSON format and when you need parse the field.
Ex:
a = JSON.parse('{"k1":"val1"}')
a['k1'] => "val1"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With