Embedded documents before_validation can't remove associated

65 views
Skip to first unread message

Scott Walker

unread,
Aug 22, 2012, 10:07:19 AM8/22/12
to mon...@googlegroups.com
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?  

Durran Jordan

unread,
Aug 29, 2012, 3:19:36 AM8/29/12
to mon...@googlegroups.com
The problem here is even though embedded documents in embed_many behave as arrays, not all operations correlate to persistence ops, since it would take quite some time to hook into every method on array to get it all working properly... So in the case of #reject! and #delete_if, I'd open an issue on Github to remind me to implement those, since actually #delete_if is implemented on has_many and has_and_belongs_to_many but I forgot to port it back to the embedded docs.

2012/8/22 Scott Walker <swal...@gmail.com>

Scott Walker

unread,
Aug 29, 2012, 8:56:29 AM8/29/12
to mon...@googlegroups.com
Reply all
Reply to author
Forward
0 new messages