Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

On create error, should I render `new` or redirect to `new`?

Suppose I have something like this:

def new
  @user = User.new
end
def create
  @user = User.create(params[:user])
  if @user.save
    flash[:notice] = 'User created'
    redirect_to :action => 'list'
  else
    flash[:error] = 'Some error here!'
    render 'new'
  end
end

I think the code is clear.
The problem here is, when the @user object is not saved successfully, should I render new (as above) or should redirect to new?

I know if redirect to new the data input by the user is lost, but if I render new, the URL will be /users/create instead of /users/new (which is ugly!).

like image 804
Omid Kamangar Avatar asked Jul 30 '12 08:07

Omid Kamangar


People also ask

What is difference between render and redirect?

There is an important difference between render and redirect_to: render will tell Rails what view it should use (with the same parameters you may have already sent) but redirect_to sends a new request to the browser.

What is the difference between render and redirect in Django?

The render function Combines a given template with a given context dictionary and returns an HttpResponse object with that rendered text. You request a page and the render function returns it. The redirect function sends another request to the given url.

What is render new?

In fact render 'new' is just a shortcut to render 'app/views/clients/new. html. erb' . The two endpoints share a view - nothing else.

How do I redirect to the same page in Ruby on Rails?

you can use redirect_to :back Method. After executing the controller, it will reload the same page.


1 Answers

You are correct in not using redirect. Redirect is loading an entirely new resource.

render however will keep your session data fresh, and depending on how your form is set up, should repopulate whatever data was inputted.

You mention:

I know if redirect to new the data input by the user is lost, but if I render new, the URL will be /users/create instead of /users/new (which is ugly!).

No, this is not true. If you say render 'new', it will go to the url users/new not create. Create as an action only handles POST requests to your controller, and generally never has a view associated with it. It will instead refer to the new action to handle any errors and displaying of forms.

The create action has this in common with the update action which does the same thing by handling only PUT requests, but refers to the edit action to handle the displaying of views.

like image 131
Trip Avatar answered Oct 11 '22 08:10

Trip