如果您在創建記錄時保存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