pingu
pingu

Reputation: 8827

Avoid index url after failing create

When you create a User in rails through the create action, the url is changed to

http://myapplication.com/users with POST

before being redirected elsewhere. If validation fails, it appears that the above URL is retained. If you then refresh, you end up on the index page (as it's now a GET).

I would expect if validation was failed the url would remain as

http://myapplication.com/users/new

As i don't have an index page, this is causing me problems. Is there a way to resolve this please?

Upvotes: 0

Views: 118

Answers (2)

Thanh
Thanh

Reputation: 8604

In your UsersController, do like this:

def new
 @user =  User.new
end

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

 if @user.save
   redirect_to root_url # save success will return to root page
 else
   render 'new'
 end
end

Upvotes: 0

mccannf
mccannf

Reputation: 16659

This depends on the logic in the respond_to block in your controller.

This is a typical example of the create action in users_controller.rb:

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

   respond_to do |format|
     if @user.save
       format.html { redirect_to @user, notice: 'User was successfully created.' }
       format.json { render json: @user, status: :created, location: @user }
     else
       format.html { render action: "new" }
       format.json { render json: @user.errors, status: :unprocessable_entity }
     end
   end
 end

So if the save fails, the new action is rendered again.

Upvotes: 1

Related Questions