what is the difference between link_to, redirect_to, and render?

后端 未结 9 804
余生分开走
余生分开走 2020-12-09 08:16

I am confused about the main difference(s) among link_to, redirect_to and render in Rails. anyone can please explain.

9条回答
  •  天命终不由人
    2020-12-09 08:41

    From the Documentation:

    Regarding rendering a view vs redirecting a request

    . . . render tells Rails which view (or other asset) to use in constructing a response. The redirect_to method does something completely different: it tells the browser to send a new request for a different URL.

    Regarding rendering a view

    . . . render :action doesn't run any code in the target action . . .

    Regarding redirecting a request

    . . . Your code stops running and waits for a new request for the browser. It just happens that you've told the browser what request it should make next, by sending back an HTTP 302 status code.


    Basically:

    link_to is a helper method to generate URLs usually used in your views (.html.erb files)

    render tells your controller to render a view without passing any data (say, from a form) to the next controller action.

    redirect_to does a 302 page redirect, passing data (say, from a form) to either a controller action on your web app, or an external app (ex: google, facebook, a web article you liked, etc)

提交回复
热议问题