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

时间:2012-05-18 02:14:44

标签: ruby-on-rails mongoid

我有以下内容:

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对象。这意味着当您保存用户时,它需要:password和:password_confirmation来保存。

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

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

“current_user”保存正常,因为它已经过身份验证,但following_user没有,因为它验证缺失:password和password_confirmation。

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

我尝试在反向的两边附加“validate:false”,但它没有任何区别。 (在这种情况下,我理解了验证选项吗?)

处理此方案的推荐方法是什么? 谢谢。

1 个答案:

答案 0 :(得分:1)

在设计密码的设计中,验证为

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

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