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?