Mongoid: disabling validation on inverse objects w

2019-08-07 05:34发布

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条回答
疯言疯语
2楼-- · 2019-08-07 06:24

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.

查看更多
登录 后发表回答