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

class Friend < ActiveRecord::Base
  belongs_to :user
end

A user will keep adding friends via a 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 the validation such that:

  • only new friends are added (i.e. John)
  • without duplicating existing ones (i.e. Paul, Mary)
  • don't failed the API call as a whole
ohho
  • 50,879
  • 75
  • 256
  • 383

0 Answers0