Search code examples
mongoidnested-forms

Using a :reject_if to test uniqueness


I've been using accepts_nested_attributes_for with embedded models for a while. For mass assignment and ryanb's nested-forms gem it is practically required. Usually, it is used like this with a lambda function to verify the parameters hash so mass assignment doesn't fail with validation errors (while still being valid) if the user doesn't place any input.

class User
  include Mongoid::Document 
  embeds_many :comments
  accepts_nested_attributes_for :comments, :reject_if => lambda { |c| c[:comment].blank? }
end

class Comment
  include Mongoid::Document 
  embeds_in :user
  
  fields :comment

  validates_presence_of :comment
end

What that does, I assume, with the :reject_if is remove the blanks from parameters before validation. What I want to do is evaluate uniqueness as well with validates_uniqueness_of and a lambda block.

I could loop through the comments (self.comments) but I assume there is some better way of doing this. I know that this would also cause uniqueness validation errors to fail silently but I am just wondering how it could be done.


Solution

  • The answer was half way down in the the related column here: validates_uniqueness_of in destroyed nested model rails

    The validation can be modified to not add errors but to reject erroneous data. That will pass the uniqueness validation in the embedded model while stripping duplicates (with a message that that was done).