Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
like image 348
Amirol Ahmad Avatar asked Sep 04 '26 05:09

Amirol Ahmad


1 Answers

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.

like image 177
Sravan Avatar answered Sep 05 '26 19:09

Sravan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!