Rails render route path

做~自己de王妃 提交于 2019-12-02 07:54:12

问题


Im still new to Rails and have a hard time understanding how the path system works in Rails.

In my routes.rb i create an alias for signup:

match 'signup' => 'user#new'
resource :user, :controller => 'user'

The action is there and going to /signup shows the correct action. So far so good.

Now, when i submit my signup form it runs the create action with POST as usual. And here is where im stuck.

If the signup fails, i would like to present the user with the signup form again. One option would be to do a render "new", but that takes the user to /user instead of /signup.

UserController

class UserController < ApplicationController

  def new
    @user = User.new
  end


  def create

    @user = User.new(params[:user])

    if @user.save
      redirect_to root_url
    else
      render "new"
    end

  end

end

Any help appreciated!

UPDATE - SOLUTION FOUND

Added 2 match routings for /signup, using the :via option

match 'signup' => 'user#new', :as => :signup, :via => 'get'
match 'signup' => 'user#create', :as => :signup, :via => 'post'

This way the application knows that when posting to /signup it should run the create action, and when http method is get, it uses the new action.

Controller markup is the same as posted above.


回答1:


Try adding the ":as" to you route like this:

match 'signup' => 'user#new', :as => :signup

and then do

redirect_to signup_url

in your controller.

That worked for me. I still don't know why. Maybe someone else has an explanation.



来源:https://stackoverflow.com/questions/7533061/rails-render-route-path

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!