验证accepts_nested_attributes_for模型的唯一性

时间:2012-05-04 02:57:07

标签: ruby-on-rails validation

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

class Friend < ActiveRecord::Base
  belongs_to :user
end

用户将继续通过REST API添加朋友:

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

稍后,用户将添加更多朋友并调用相同的API:

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

现在,我应该如何编写验证:

  • 只添加了新朋友(即约翰)
  • 不重复现有的(即Paul,Mary)
  • 整个API调用都没有失败

0 个答案:

没有答案