Create a json object from a Rails form

I have a Ruby on Rails form that takes input and saves it as model attributes. However, one of the attributes contains json data. I would like to be able to accept data entered into a number of fields, and save them as a JSON object attribute my models. Can I do it?

If it helps, I can also make a hash and convert it to json. Basically, I just want to combine several input fields into one, and then give it from there.

Thanks!

+4
source share
4 answers

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.
+13
source

You can save all multiple files as plain text in JSON format and when you need to analyze the pitch.

Example:

 a = JSON.parse('{"k1":"val1"}') a['k1'] => "val1" 
+2
source

Probably you are looking for before_save , which takes all of your attributes model and creates a JSON format using the method .to_json .

0
source

You should probably see the new Postgres JSONB format. I think this gives you all the PROS, and none of the CONS:

http://robertbeene.com/rails-4-2-and-postgresql-9-4/

0
source

All Articles