【发布时间】:2016-12-01 01:11:31
【问题描述】:
我在表“配置”中有 1 个名为“message_notification”的列。我想在此列中生成保存结果为 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 %>
如何做到这一点?
[更新]
以上代码将解析为 ruby 哈希(而不是 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
【问题讨论】:
-
你做得很好,有什么问题?
-
@AnujDhanju 我已经更新了我上面的问题
-
您可以在
require 'json'上使用to_jsonhash -
@Sravan 是的,我在我的控制器中做到了这一点.. 但仍然产生
=>.. 请参阅上面的更新 -
检查,
puts { 'alert' => params[:message][:alert] }.to_json
标签: ruby-on-rails json ruby ruby-on-rails-4