Ruby on Rails登录IF语句验证功能失效问题求助
Hey there! Let's figure out why your email verification check isn't working and get it sorted out quickly.
The Core Issue in Your Code
Looking at your current logic, the problem is right here:
confirmationtoken = User.find_by_confirmation_token(params[:confirmation_token].to_s)
When a user is trying to log in, they only submit their email and password—they don't send a confirmation_token parameter (that's only used when they click the verification link in their email). This means this line will always return nil, so your first if condition never triggers, and the "Email not verified" error never shows up when it should.
You don't need to query for a separate user by token—you already have the user associated with the login email! You just need to check that user's confirmation_token field.
Corrected Code
Here's the fixed version of your authenticate method:
def authenticate(email, password) # First, fetch the user by their login email user = User.find_by(email: email) # Run your authentication command command = AuthenticateUser.call(email, password) # Check if the user exists AND still has a confirmation token (unverified) if user.present? && user.confirmation_token.present? render json: { error: 'Email not verified' }, status: :unauthorized elsif command.success? render json: { access_token: command.result, message: 'Login Successful' } else render json: { error: command.errors }, status: :unauthorized end end
Key Changes Explained
- Fetch the user first: We get the user associated with the provided email right at the start, so we can check their verification status directly.
- Check the user's own token: Instead of looking for a random token from params, we check if the logged-in user still has a
confirmation_tokenvalue. If they do, that means they haven't verified their email yet. - Logical flow: We moved the verification check to the top, so it runs before we even attempt to authenticate the password—this makes the logic more intuitive and ensures the unverified error takes priority.
Quick Double-Check
Just make sure that when a user clicks the verification link, your code is properly setting their confirmation_token to nil (or deleting it entirely). You mentioned this part works, but it's worth confirming that field is actually being cleared after verification—otherwise the check will still fail!
内容的提问来源于stack exchange,提问作者Ray Zuchowski

