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])
respon开发者_如何学Pythond_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!
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.
精彩评论