Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails render "action" as custom url

In my routes.rb I have the following:

get "contact" => "inquiries#new"

So that when I go to /contact in the browswer, it calls the InquiriesController's new action.

Now when I try to call render "new" in the create action inside InquiriesController:

def create
    …
    render "new"
end

The resulting url in the browser is /inquiries.

Is there a way besides calling redirect_to to render "new" but have the url as /contact in the browser?

like image 878
user2345093 Avatar asked Nov 28 '22 15:11

user2345093


1 Answers

Short answer is No. And here's why:

render is different from redirect_to. When you write redirect_to :action, you are initiating an entirely new browser request. The rails stack is hit, again routes are searched for and the corresponding action is executed. Its exactly the same as entering the url in address bar and pressing enter.

On the other hand, when you use render, you are telling which view to use for the current request. As such, the address in the address bar will generally be of the action in which you are calling render. That's because you put an address and then you tell rails to display a different page in that same request.

In a nutshell, while redirect_to begins an entirely new request cycle, render simply replaces the default view with what you choose in the same request cycle.

So if you want the address bar to change, you will have to initiate a new request to the address you want. It can be by manually entering the address, clicking a link to that address or redirecting to it from rails.

Hope this helps.

like image 153
Akash Avatar answered Dec 05 '22 22:12

Akash