レコード作成時にhas_many:throughアソシエーションを保存する場合、アソシエーションに一意のオブジェクトがあることをどのように確認できますか。一意性は、カスタム属性セットによって定義されます。作成時に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と役割を検証するための最良の方法は何ですか
は、協会の任意の条件に基づいてユニークですか?
ありがとうございました。しかし、これは検証エラーには良いですが、実際に検証する前にどのようにサニタイズするのかというだけでなく、単にエラーを出力するのではないでしょうか。誰かが同じ役割を2回実行すると、エラーを投げて修正することができます。あるいは、良いユーザーエクスペリエンスを提供して重複排除できます。 –
'valid? 'のようなことをすれば、エラーは発生せず、エラーの性質に基づいてユーザーに特定のフィードバックを提供することができます。それはかなり標準的なSOPです。 'valid?'や 'save'や' create'など何かをしようとする前に手作業によるチェックを自分で行うことができますが、ActiveRecordの機能を複製するだけなので、なぜそうするのか分かりません。 – jvillian