Uniqueness check for accepts_nested_attributes_for model

class User < ActiveRecord::Base
  has_many :friends
  accepts_nested_attributes_for :friends
end

class Friend < ActiveRecord::Base
  belongs_to :user
end

The user will add friends through the REST API:

{ "user": {
        "name": "Peter",
        "friends_attributes": [
            { "name": "Paul" },
            { "name": "Mary" }
        ]
    }
}

Later, the user will add more friends and call the same API:

{ "user": {
        "name": "Peter",
        "friends_attributes": [
            { "name": "Paul" },
            { "name": "Mary" },
            { "name": "John" }
        ]
    }
}

Now, how should I write a check so that:

  • only new friends added (i.e. John)
  • without duplication of existing ones (i.e. Paul, Mary)
  • failed to call the API call in general
+3
source share

All Articles