Finnnn
Finnnn

Reputation: 3580

Redirect to a custom path on failure to upate

I have a route set up like this -

  match "/:id" =>"car#edit", :as => :edit_car
  match "/:id/thanks" =>"cars#thanks", :as => :thanks

www.myurl.com/12345 will go to the edit action of car.

My update action looks like this

def update
  @car = Car.find(params[:id])
  respond_to do |format|
    if @car.update_attributes(params[:car])
      format.html { redirect_to(thanks_path(@car)) }
    else
      format.html { render action: "edit" }
    end
  end
end  

On a successful update it redirects to www.myurl.com/12345/thanks - which is good - works as expected.

However, when it has errors while updating it renders the edit action as -

  www.myurl.com/cars/12345

I'd like it to rerender the edit action as -

  www.myurl.com/12345

I'd like make sure that error messages are still sent through. Is this possible?

Upvotes: 0

Views: 99

Answers (1)

mark
mark

Reputation: 10564

The route you're seeing is the edit action of the resource route, not your separately defined edit action. Hence it includes the controller in the path.

If you want that the path not include the cars controller you can include this in the route definition:

resources :cars, :path => '/'

From experience I advise that you don't do that as things get messy when you want to expand your application.

I suggest you do away with the defined edit action and edit your cars from the show action of your resource route. Also, you could display the success message from the update action without redirecting by having an update view file.

If you do want to redirect you can modify resource routes as so:

resources :cars, :path => '/' do
   member do 
     get 'thanks'
   end
end

Upvotes: 1

Related Questions