I have the following models setup:
class Exercise
include Mongoid::Document
field :name, type: String
embeds_many :measurements, as: :measurable
accepts_nested_attributes_for :measurements, :recject_if => :all_blank, :allow_destroy => true
validates :measurements, presence: true
before_validation do |doc|
doc.measurements.reject! { |m| m.name.downcase != "distance" }
end
end
class Measurement
include Mongoid::Document
include Mongoid::Timestamps
field :name, type: String
field :uom, type: String
field :value, type: Integer
embedded_in :measurable, polymorphic: true
validates :name, :presence => true, :uniqueness => { :case_sensitive => false }
validates :uom, :presence => true
attr_accessible :_type, :name, :uom, :value
end
I am using fields_for on my exercise form to post nested attributes for measurements when creating an exercise. The measurements are getting posted and saved as expected.
The problem I am having is that the before validation on Exercise is not actually removing the embedded measurement documents that don't match the name "distance".
If I put a debugger statement right after the reject! call the doc clearly no longer has any measurements other than distance listed for doc.measurements, however once the save actually completes the document that gets persisted still has all of the posted measurements, including the ones rejected by the before_validation callback.
I have noticed that this kind of functionality works totally fine with Array fields, so I can only conclude that it has something to do with it being an embedded document.
Am I just doing something totally boneheaded and you can't remove embedded documents in this fashion, or is this a problem of some kind?