如果您在创建记录时保存has_many:through关联,如何确保关联具有唯一对象。唯一性由一组自定义属性定义。确保has_many:通过关联在创建时是唯一的
考虑:
class User < ActiveRecord::Base
has_many :user_roles
has_many :roles, through: :user_roles
before_validation :ensure_unique_roles
private
def ensure_unique_roles
# I thought the following would work:
self.roles = self.roles.to_a.uniq{|r| "#{r.project_id}-#{r.role_id}" }
# but the above results in duplicate, and is also kind of wonky because it goes through ActiveRecord assignment operator for an association (which is likely the cause of it not working correctly)
# I tried also:
self.user_roles = []
self.roles = self.roles.to_a.uniq{|r| "#{r.project_id}-#{r.role_id}" }
# but this is also wonky because it clears out the user roles which may have auxiliary data associated with them
end
end
什么是验证user_roles和角色的最佳方式是独特的基于关联任意条件?
谢谢。但是这对验证错误很有用,但是,问题实际上是如何在验证之前进行消毒,而不是简单地将错误消除。如果有人放置相同的角色两次,我*可能会抛出一个错误并让他们修复它,或者我可以提供良好的用户体验并为其重新进行删除。 –
如果你做了'valid?'之类的事情,你就不会抛出错误,并且可以根据错误的性质向用户提供具体的反馈。这是一个非常标准的SOP。你可以在尝试'valid''或'save'或'create'之前自己做一些手动检查,但是你只是在复制ActiveRecord的功能,我不知道你为什么要这么做。 – jvillian