I am using Devise for my authentication. If a hashed_password
isn't set, Rails/Devise's validations will require a password to be set, as well as the password_confirmation
.
When I invite new users, I obviously don't want to set their password, so when I create the invitation in my system, it fails because user.password
is blank.
I can set a temporary hashed_password
on the user, but when they enter their own password, the validation checks for :password
and :password_confirmation
will not happen because hashed_password
is set, which is a real problem.
Is there any way to tell Rails that I want to run all the validations except for the ones associated with :password
?
I know Rails has :if
conditions, which might fix my problem, but Devise declares the :password
validation on my behalf, so that essentially is hidden.
How can I get the desired result here?, hopefully in a way that is not a hack.
My current hypothetical solution that is somewhat messy: The only thing I can think of is to create a new Invitation model that is not the User model, and use the Invitation model for the form. When the invitation is submitted I can validate that Invitation and copy over all the values to the new User model. I can save that User without any validations at all.
That's the best solution I dreamed up.
It seems like my solution will be a lot more work than saying something simple like:
user.save(validations => {:except => :password})
EDIT: I have found one part of the solution, but I am still having problems. In our user model, we can override a Devise method to prevent the validation of the password for invitations with this bit of code:
#protected
def开发者_运维问答 password_required?
!is_invited && super
end
The is_invited
attribute is just a column I added to the users
table/model.
However, there is one gotcha here. When a user accepts an invitation and they arrive to the form where they need to set their password/password_confirmation, valid?
will always return true
.
This one has me deeply perplexed. I don't see how requires_password?
and valid?
can be true at the same time. If it requires the password, it should do a validation check and cause the validations to fail.
I'm starting to hate Devise - or just the idea of using gems to build parts of your application in a blackbox. I think the real solution probably is to rip out Devise and just do it all from scratch. That way your app has total control of how all of this works :(
I recently started using this great devise add-on: devise_invitable
It's commonly used so users (or any model) can invite other users to join.
But I adapt it for manually (via an admin panel) invite new potential users to my app.
Hope this helps!
精彩评论