我在表'配置'中有一列名为' message_notification '的列。我想在此列中将保存结果作为JSON对象生成:
border-color:transparent
表格,我用
message_notification: [
{
"alert" : "how are you doing today?"
},
{
"alert" : "where have you been today?"
}
]
如何实现这一目标?
[增订]
上面的代码将解析为ruby哈希(而不是JSON)
我的控制器
<%= 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 %>
结果:
@configuration.message_notification = {
alert: params[:message][:alert]
}.to_json
[更新2]
在控制台中:
message_notification: [
{
"alert" => "how are you doing today?"
},
{
"alert" => "where have you been today?"
}
]
答案 0 :(得分:2)
您可以使用 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
,并存储在数据库中。
答案 1 :(得分:0)
这就是我所做的。
def resource_params
params.require(:appointment_modules_dataset_intake).permit(
:appointment_id,
:main_issue,
:cvf
).tap do |p|
p[:cvf] = JSON.parse(p[:cvf]) # This is the significant line
end
end