我在“配置”表中有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
您可以使用to_json
将转换ruby hash
为JSON object
只是require 'json'
在你的controller
。
params = {"utf8"=>"✓", "_method"=>"new", "authenticity_token"=>"txroAHF2+YZOrm48DtBZdVqKzxLYyHFq4+GWQFnM6kNldXgRZJMPv0yfj0/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)
这会将message_notification
参数中的转换为json object
,并存储在DB中。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句