Rails Devise控制器间传参问题:注册后重定向至原课程页
Hey there! I’ve run into a similar issue before, so let’s break down how to get this working properly. The core problem here is making sure the course_id parameter travels all the way from the course page through the registration form to the controller’s create action. Here’s what you need to do:
1. Pass the course_id through the Registration Form
Even though you see the course_id in the registration page’s URL, that parameter won’t automatically carry over when you submit the form. You need to add a hidden field to your registration form to explicitly send it along with the POST request:
# In your registration form view (e.g., app/views/users/new.html.erb) <%= form_with(model: @user) do |form| %> # ... your existing form fields ... # Add this hidden field to pass the course_id <%= hidden_field_tag :course_id, params[:course_id] %> <%= form.submit "Register" %> <% end %>
This ensures that when the form is submitted, the course_id is included in the params sent to your controller.
2. Use the course_id in Your Controller’s Create Action
Next, update your registration controller’s create action to grab the course_id from params and use it to build the redirect path. Make sure you’re accessing it directly from params (not nested under :user, since it’s a standalone parameter):
# In your UsersController def create @user = User.new(user_params) if @user.save # Grab the course_id from the submitted params target_course_id = params[:course_id] if target_course_id.present? # Redirect to the course page using the dynamic ID redirect_to course_path(target_course_id), notice: "Successfully registered! Welcome back to the course." else # Fallback redirect if no course_id was provided redirect_to root_path, notice: "Successfully registered!" end else render :new end end # Make sure your user_params method doesn't try to permit course_id (it's not a user attribute) private def user_params params.require(:user).permit(:email, :password, :password_confirmation) # Add your user attributes here end
3. Add Robustness (Optional but Recommended)
To avoid errors if an invalid course_id is passed, you can fetch the course object first instead of using the ID directly:
if target_course_id.present? course = Course.find_by(id: target_course_id) if course redirect_to course, notice: "Successfully registered! Welcome back to the course." else redirect_to root_path, alert: "The course you were viewing couldn't be found." end else redirect_to root_path, notice: "Successfully registered!" end
4. Debugging Tip
If you’re still having trouble, add a puts params line at the start of your create action and check your Rails server logs. This will show you exactly what parameters are being sent, so you can confirm if course_id is coming through correctly.
That should do it! When users register from a course page, they’ll now be redirected right back to that course after a successful registration.
内容的提问来源于stack exchange,提问作者Bradley

