Here you need to consider a few things.
The first challenge is to get your data from the form HTML. If you are using a standard way for the Rails naming input form, it is 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 call them so they can get access to a "en bloc", using the hash params through the params[:my_fields] , which will give you another hash containing your data.
Then you need to choose how to store this data in your model. There are several options:
1. Use a string attribute
Just use the column string or text and assign a JSON string:
@my_model.my_data = params[:my_fields].to_json
- Pro: very simple solution.
- Contra: SQL queries are nearly impossible. Rails processing requires manual analysis of a data string.
2. Use a serialized hash
Use column string or text and declare it as being serialized in your model
serialize :my_data, Hash
Then you can use this column as it was a simple hash, and Rails will execute read and write operations.
@my_model.my_data = params[:my_fields]
- Pro: Still a simple solution. Do not interfere with JSON strings. Treatment with Rails much easier.
- Contra: SQL queries are nearly impossible. Call
to_json needs, if you need the real string JSON.
3. Use specialized types of JSON data
If you need to be able to query the database using SQL, you the above solutions do not work. For this you need to use special types.
Many DBMSs provide structured data types in the form of XML or even JSON types. (E.g. PostgreSQL)
- Pro: possible database queries.
- Contra: Requires custom parsing and serialization, as well as migration. This solution may be overdesigned.
source share