Why is Rails 3.2.2 Generating URLs prefixed with /assets when using redirect_to?

Go To StackoverFlow.com

4

Well the title Question pretty much sums it up, But I'd like to detail a scenario anyways,

I've created a DemoController, (I have not created a Resource model), and my routes.rb looks like this:

DispatchMe::Application.routes.draw do
  root to: "demo#index"
end

From the demo controller I'm dong the following:

class DemoController < ApplicationController
  def index
    redirect_to :action => 'show'
  end

  def show
  end
end

There is a file in: app/views/demo/show.html.erb of course, And I'd expected that template to be rendered but instead I'm getting the following error:

ActionController::RoutingError (No route matches [GET] "/assets")

and this URL is generated as a result from the redirect:

/assets?action=show&controller=demo

Am I missing something here? I thought rails was supposed to render the action's template for such cases.

Note. I understand that If I create a route like get 'show' => "demo#show" and call redirect_to show_path it'll work just fine, But I need to know if that's mandatory?

Thank you very much!

2012-04-03 21:12
by jlstr


1

For the desired behavior, use render instead of redirect_to:

class PagesController < ApplicationController
  def index
    render :action => "show"
  end

  def show
  end
end

EDIT:

You can use redirect_to on other actions, but from what I can tell, the index action sets the base path. To simplify route definition, use resources :controller_name. You can view the routes generated by resources by typing rake routes in your command line.

Example:

demo_controller.rb

class DemoController < ApplicationController
  def index
  end

  def show
    redirect_to :action => 'index'
  end
end

routes.rb

DispatchMe::Application.routes.draw do
  root to: "demo#index"
  resources :demo
end

development.log

Started GET "/demo/show" for 127.0.0.1 at 2012-04-04 14:55:25 -0400
Processing by DemoController#show as HTML
  Parameters: {"id"=>"show"}
Redirected to http://dispatch.dev/
Completed 302 Found in 0ms (ActiveRecord: 0.0ms)
2012-04-04 15:50
by Ezekiel Templin
Yes, I was beginning to realize that myself. However to me, it seems almost unacceptable that rails doesn't permit to use redirect_to without a route definition. render works, but will not update the current URL, which isn't for this case a desired behavior. I wish someone who has large experience with RoR could explain to me why this is currently working like this - jlstr 2012-04-04 16:51
@user766388 I've updated my answer. Let me know if you'd like a code example - Ezekiel Templin 2012-04-04 17:18
Nice, Your explanation is a lot better. But since you have offered, I can't miss the opportunity to have an example. I would really like to see it. Thank you very much - jlstr 2012-04-04 18:48
I've updated my example - Ezekiel Templin 2012-04-04 18:57
Thank you for the example and all the help provided Sir - jlstr 2012-04-04 20:24