2016-12-01 30 views
1

我有1列名爲'message_notification'內部表'配置'。我想製作保存結果作爲JSON對象在此列:Rails 4:將值保存爲PostgreSQL中的JSON字符串對象/數組

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

的形式,我使用

<%= 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 %> 

如何實現這一目標?

[增訂]

上面的代碼將解析爲紅寶石散列(不作爲JSON)

我的控制器

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

結果:

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

[增訂2]

在控制檯:

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

你做得很好,問題是什麼? –

+0

@AuujDhanju我已經更新了我的問題 – AmirolAhmad

+0

以上你可以'require'json''並在''hash'上使用'to_json' – Sravan

回答

2

可以使用,to_json轉換的ruby hashJSON object

只是require 'json'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"}} 

由於您params object以上,根據您的要求,您可以使用,

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

這在PARAMS的message_notification轉換爲json object,並存儲在數據庫中。

相關問題