【发布时间】:2017-07-14 21:58:00
【问题描述】:
如果您在记录创建时保存 has_many :through 关联,您如何确保关联具有唯一对象。唯一性由一组自定义属性定义。
考虑:
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 和角色是否唯一的最佳方法是什么?
【问题讨论】:
标签: ruby-on-rails activerecord associations