简体   繁体   中英

how to route to a different page in ruby on rails

I have a session controller like

def create
    user = User.find_by_email(params[:session][:email])
    if user && user.authenticate(params[:session][:password])
      sign_in user
      redirect_to user
    else
      flash.now[:error] = 'Invalid email/password combination' # Not quite right!
      render 'new'
    end
  end

if you notice on successful sign in it does redirect_to user which is the show action in the User controller.

But say instead of that I have to go to the new action of user controller then how do i do that?

redirect_to user is just a shortcut for redirect_to url_for(user) , which generates the url for a given resource ( url_for ) and then redirects to it.

If you want to redirect to another url, you can use the path helper.

redirect_to new_user_path

You could also use the url_for helper to generate an url.

redirect_to url_for(:controller => "users", :action => "new")

Which can be shortened to

redirect_to :controller => "users", :action => :new

You can even specify an url directly ( redirect_to '/users/new' ) - which I would not recommend, as you can't change your routing later without changing all the urls.

The docs

As you can see, there are many ways to specify an url to redirect_to in rails. Take a look at the documentation for all of them

To render an action from another controller:

render 'users/new'

See: http://guides.rubyonrails.org/layouts_and_rendering.html#using-render

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM