0

I have a Pages model with field 'customURL'. I can do page#show at '/:customurl'. but because i've defined page show that way in routes, my create action now does a redirect on success to the wrong route. What should I change to most cleanly fix the redirect properly to point to '/:customurl' on save?

controller:

def create
  @page = Page.new(params[:page])

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

routes:

resources :pages
...
get "/:customURL" => "pages#show"

Thanks!

tuddy
  • 1,824
  • 4
  • 31
  • 35

1 Answers1

1

In routes.rb, you can add magic helpers.

get "/:customURL" => "pages#show", :as => :custom

Then in your controller

format.html { redirect_to custom_url(@page. customURL), notice: ... }

Now, "/:customURL" will need to be last in your routes.rb, routes are greedy, the first to match will get it. So if you have something like "/bob" and you have a controller listening at "/bob", the controller will get it before the pages controller.

Travis
  • 10,444
  • 2
  • 28
  • 48
  • Ok, hmmm this is crashing my server currently. I get this in the logs: `Exiting .../config/routes.rb:18:in `block in ': undefined local variable or method `custom' for # (NameError)` let me know if there's a tweek i need here or if you possibly need more code... Do I need to add route helpers or something somewhere? – tuddy Oct 11 '11 at 15:53
  • Ok, using what you have I was able to piece it together. This is what worked for me, maybe edit your answer accordingly? In routes: `get "/:customURL" => "pages#show", :as => :pageshow` and in controller `format.html { redirect_to pageshow_path(@page.customURL),...` – tuddy Oct 11 '11 at 16:07
  • Sorry, it's `as: :custom`. I'll fix that! – Travis Oct 11 '11 at 17:27
  • Can you add the other things i put in my comment? if you want to use custom in stead of 'pageshow' that's cool. In other words, just make it :as => and do @page.customURL? That worked for me anyways. thanks again. – tuddy Oct 11 '11 at 17:35
  • Sure, `:as => :custom` is the same as `as: :custom` in newer ruby. Ruby added the JSON style (?) hash identifiers in addition to the hash-rocket (`=>`). However, I'm happy to adjust. Glad you got it working. – Travis Oct 11 '11 at 18:10