Mongoid: disabling validation on inverse objects when saving parent for HABTM relationship Options

我的未来我决定 提交于 2019-12-11 11:40:58

问题


I have the following:

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

Note that User is also a Devise object. This means that when you save a User it requires :password and :password_confirmation to save.

In the context of a rails app using Devise, and I have access to the current_user who is the currently signed in user:

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

"current_user" gets saved ok because it is authenticated, but following_user does not because it fails validation for missing :password and :password_confirmation.

Is there anyway that I can disable the validation on the inverse objects?

I tried appending "validate: false" to both sides of the inverse, but it didn't make any difference. (Have I understood the validate option in this case?)

What is the recommended approach to deal with this scenario? Thanks.


回答1:


In Devise validations for password is given as

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

and the method password_required is

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

you can overwrite this method in your user model with your required logic.



来源:https://stackoverflow.com/questions/10645898/mongoid-disabling-validation-on-inverse-objects-when-saving-parent-for-habtm-re

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!