Rails 4.2.8邮件激活页面添加邮箱地址技术咨询
Hey there, let's get that email address showing up on your email_confirm.html.erb page. Since you're working with Rails 4.2.8 and Ruby 2.5.0, here's a straightforward implementation tailored to your setup:
Step 1: Pass the User Instance to the View from Your Controller
First, your controller needs to send the user's data (including their email) to the confirmation view. Depending on how your registration flow works, use one of these scenarios to retrieve the user:
Scenario 1: User arrives via activation link (with token)
If users land on this page after clicking an activation link with a token in the URL:
# app/controllers/users_controller.rb def email_confirm # Fetch the user using the activation token from URL params @user = User.find_by(activation_token: params[:token]) # Handle invalid/expired tokens or already activated accounts if @user.nil? || @user.activated? flash[:alert] = "Invalid or expired activation request. Please check your email or register again." redirect_to root_path end end
Scenario 2: Direct redirect after registration (no token)
If users are sent here immediately after signing up (store their ID in the session during registration):
# app/controllers/users_controller.rb def email_confirm # Retrieve the user from the session (set this in your #create action post-registration) @user = User.find(session[:registered_user_id]) # Clean up the session to prevent accidental reuse session.delete(:registered_user_id) rescue ActiveRecord::RecordNotFound flash[:alert] = "We couldn't find your account. Please try registering again." redirect_to root_path end
Step 2: Display the Email in Your View
Update your email_confirm.html.erb to show the user's email. Insert this right below your existing "Please Activation account:" heading to match your page's flow:
<div class="pd10 bgCo"> Please activate your account for the email address: <span class="text-yellow"><%= @user.email %></span> </div>
Optional: Add Error Handling in the View
Make sure to display any flash alerts if something goes wrong (like an invalid token):
<% if flash[:alert] %> <div class="alert alert-danger pd10"> <%= flash[:alert] %> </div> <% end %>
Step 3: Test the Flow
- Registration test: After signing up, confirm the user is redirected to
email_confirmand their email displays correctly. - Invalid request test: Try accessing the page with a bad token or without a valid session user to ensure error messages appear as expected.
That's it! This fits Rails 4.2.8's conventions and ensures the email is displayed securely and clearly to your users.
内容的提问来源于stack exchange,提问作者SylorHuang

