Amirol Ahmad
Amirol Ahmad

Reputation: 542

Rails JSON : Empty/Blank data will not save in database

I have this in my controller

@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

will produce JSON:

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

As you can see in the JSON, empty data (mode & remind_interval) still save in db. how to avoid this so will produce just only attr with data:

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

Upvotes: 1

Views: 489

Answers (2)

Jagdeep Singh
Jagdeep Singh

Reputation: 4920

Try this solution please:

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

Upvotes: 0

Mikhail Chuprynski
Mikhail Chuprynski

Reputation: 2493

Well, it seems to me there are some fundamental issues here.

First of all, a controller is not a good place to do this kind of stuff.

Second, you should pass this logic to database wrapper, like active record or mongoid.

Or you could do it quick and dirty:

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

Upvotes: 2

Related Questions