2

I'm using Rails 4.2 and using the .update_attributes method.

After some debugging it's come to my attention that if the field is MISSING from the params, Mongoid will just keep the old value of the param.

Edit: It seems that no matter what I do, the following code doesn't work:

campaign = Campaign.find_by username: params[:id]
campaign.update_attributes params[:campaign].permit!

Here's what does work:

campaign.attributes = params[:campaign].permit! 
# .update_attributes(params[:camapign]) would likely work, too
campaign.allowed_brokers = params[:campaign][:allowed_brokers]
campaign.custom_payouts = params[:campaign][:custom_payouts]
campaign.save

Both allowed_brokers and custom_payouts are Array type fields. It seems that line 1 takes care of anything that's not an array field.

I'm 100% sure that incoming params don't contain the old values (in fact, they're missing from params[:campaign] - there's no params[:campaign][:allowed_bidders] for example.

Why is Mongoid not updating the array fields?

Thanks in advance.

PS: Here's the model:

class Campaign
  include Mongoid::Document
  include Mongoid::Timestamps
  include Mongoid::Attributes::Dynamic

  field :name,                  type: String

  # ==== Other irrelevant fields ====

  # List of brokers and corresponding share %
  field :custom_payouts,        type: Array, default: []

  # Taggable strings
  field :allowed_brokers,       type: Array, default: []
  field :allowed_bidders,       type: Array, default: []
  field :can_start,             type: Array, default: []
  field :can_pause,             type: Array, default: []

  # Associations
  has_and_belongs_to_many :bidders
end

PPS: I'm still trying to figure out why I have to manually amend the array fields. Meanwhile I've also found that despite the fact the fields are of type Array with a defined default of [], they can be set to null directly in the database which is bad. How do I avoid that? Maybe Attributes::Dynamic has something to do with that? If so, how'd I manually amend Arrays without it?

dsp_099
  • 5,801
  • 17
  • 72
  • 128
  • Yes, that was my first guess. It's EXACTLY the params I want to send, NOT including some fields. – dsp_099 Jan 23 '15 at 06:45
  • Have you looked at this answer? It might be the permit error http://stackoverflow.com/a/16555975/1769515 – a14m Jan 23 '15 at 14:28
  • i have a feeling that's not it. I looked at mongoDB docs and it seems that you have to specify explicitly which fields you're updating and since I'm not, they aren't... that's my leading theory at the moment – dsp_099 Jan 23 '15 at 18:59

0 Answers0