Rails JSON:空/空数据不会保存在数据库中

时间:2016-11-23 04:43:47

标签: ruby-on-rails arrays json ruby ruby-on-rails-4

我在控制器中有这个

@geo.message_notification = {
  trigger_event: params[:ng_geo][:trigger_event],
  ptc: {
    id: params[:ng_geo][:ptc]
  },
  message: params[:ng_geo][:message],
  mode: params[:ng_geo][:mode],
  remind_interval: params[:ng_geo][:remind_interval],
  document: {
    id: params[:ng_geo][:document]
  }
}.to_json

将生成JSON:

{
  "trigger_event":"IOR",
  "ptc":
  {
    "id":"184"
  },
  "message":"could you please be faster?",
  "mode":"",
  "remind_interval":"",
  "document":
  {
    "id":"234"
  }
}

正如您在JSON中看到的那样,空数据(mode& remind_interval)仍然保存在db中。如何避免这种情况,只会产生数据attr:

{
  "trigger_event":"IOR",
  "ptc":
  {
    "id":"184"
  },
  "message":"could you please be faster?",
  "document":
  {
    "id":"234"
  }
}

2 个答案:

答案 0 :(得分:2)

嗯,在我看来这里有一些基本问题。

首先,控制器不是做这种东西的好地方。

其次,您应该将此逻辑传递给数据库包装器,如活动记录或mongoid。

或者你可以快速而肮脏地做到这一点:

@geo.message_notification = {
...
}.select{|_,v| !v.blank?}.to_json

答案 1 :(得分:0)

请尝试此解决方案:

ng_geo_params = params[:ng_geo].slice(:trigger_event, :ptc, :message, :mode, :remind_interval, :document).delete_if { |k, v| v.blank? }
# OR if you can
ng_geo_params = params.require(:ng_geo).permit(:trigger_event, :ptc, :message, :mode, :remind_interval, :document).delete_if { |k, v| v.blank? }

message_notification_hash = {}

ng_geo_params.each do |k, v|
  if k == :ptc || k == :document
    message_notification_hash[k] = { id: v }
  else
    message_notification_hash[k] = v
  end
end

@geo.message_notification = message_notification_hash.to_json