AmirolAhmad AmirolAhmad - 9 days ago 13
Ruby Question

Rails 4 : Saving value as JSON string object/array in PostgreSQL

I have 1 column called 'message_notification' inside table 'configuration'. I want to produce save result as JSON object in this column:

message_notification: [
{
"alert" : "how are you doing today?"
},
{
"alert" : "where have you been today?"
}
]


for the form, i use

<%= simple_form_for(@configuration) do |f| %>
Alert 1: <%= check_box_tag "configuration[message_notification][][alert]", 'how are you doing today?' %><label>Alert 1</label><br/>
Alert 2: <%= check_box_tag "configuration[message_notification][][alert]", 'where have you been today?' %><label>Alert 2</label><br/>
<%= f.submit %>
<% end %>


How to achieve this?

[UPDATED]

above code will resolve as a ruby hash (not as JSON)

my controller

@configuration.message_notification = {
alert: params[:message][:alert]
}.to_json


result:

message_notification: [
{
"alert" => "how are you doing today?"
},
{
"alert" => "where have you been today?"
}
]


[UPDATED 2]

In console:

=> a = value.message_notification
=> "[{\"alert\"=>\"alert1\"}, {\"alert\"=>\"alert2\"}]"
=> puts a
=> [{"alert"=>"alert1"}, {"alert"=>"alert2"}]
=> nil

Answer

You can use, to_json to convert the ruby hash to JSON object

just require 'json' in your controller.

params = {"utf8"=>"✓", "_method"=>"new", "authenticity_token"=>"txroAHF2+YZOrm48DtBZdVqKzxLYyHFq4+GWQFnM6kNldXgRZJMPv0yfj‌​0/tfZVpuVvh39UVX4Fb66FNkkCZqA==", "message"=>{"name"=>"Dan Murphy Roundabout Test", "company"=>"transtech", "location_id"=>"", "message_notification"=>[{"alert"=>"alert1"}, {"alert"=>"alert2"}], "commit"=>"save", "controller"=>"message", "action"=>"create", "id"=>"1717"}}

Since your params object is above, according to your requirement you can use,

params['message']['message_notification'] = (params['message']['message_notification'].to_json)

this converts the message_notification in the params to a json object, and stores in the DB.