Mongoid:在为 HABTM 关系选项保存父对象时禁用对反向对象的验证



我有以下内容:

def User 
  has_and_belongs_to_many: :following, class: "User", inverse: :followers 
  has_and_belongs_to_many: :followers, class: "User", inverse: :following 
end

请注意,User 也是一个 Devise 对象。这意味着当您保存用户时,需要:p assword和:p assword_confirmation才能保存。

在使用 Devise 的 rails 应用程序的上下文中,我可以访问当前登录用户的current_user:

following_user = User.find(following_id) 
current_user.following.push(following_user) 

"current_user"保存正常,因为它已经过身份验证,但following_user不会,因为它无法验证缺少:p assword和:p assword_confirmation。

无论如何,我可以禁用对反向对象的验证吗?

我尝试将"validate:false"附加到反向的两侧,但这没有任何区别。(在这种情况下,我是否了解验证选项?

处理这种情况的建议方法是什么?谢谢。

在设计中,密码的验证如下

validates_presence_of     :password, :if => :password_required?
validates_confirmation_of :password, :if => :password_required?

password_required方法是

def password_required?
   !persisted? || !password.nil? || !password_confirmation.nil?
end

您可以使用所需的逻辑在用户模型中覆盖此方法。

最新更新