How do I force a certain URL after a Rails redirect?

时间:2016-07-11 21:31:55

标签: ruby-on-rails-4 url redirect controller

I’m using Rails 4.2.3. I have the following in the create method of my controller

    format.html { redirect_to controller: "my_objects", action: "index", notice: 'Saved successfully.' }

However when I redirect, the URL is actually

http://mydomein.devbox.com:3000/my_objects

and I want it to be

http://mydomein.devbox.com:3000/my_objects/index

How can I force the URL to be “/index” instead of what its appearing as now?

Edit: Here are the logs when visiting /my_objects/index:

Started GET "/my_objects/index" for 127.0.0.1 at 2016-07-12 12:17:25 -0500
Processing by MyObjectsController#index as HTML
DEPRECATION WARNING: Passing a nested array to Active Record finder methods is deprecated and will be removed. Flatten your array before using it for 'IN' conditions. (called  from country_code_select at /Users/davea/Documents/workspace/runtrax/app/helpers/user_form_helper.rb:83)
  Rendered my_objects/_add.html.erb (31.0ms)
  Rendered my_objects/index.html.erb within layouts/race (46.0ms)
  Rendered layouts/_navigation.html.erb (0.2ms)
  Rendered layouts/_messages.html.erb (0.1ms)
  Rendered my_objects/_tabs.html.erb (0.3ms)
Completed 200 OK in 308ms (Views: 301.9ms | ActiveRecord: 4.8ms)

Edit: Here is the relevant portion from the config/routes.rb file …

  get 'my_objects/index'
  get 'my_objects/create'
  resources :my_objects do
    collection do
      post 'create'
      get 'import'
      get 'index' => 'my_objects/index'
      get 'search'
      get 'stats'
    end
  end

3 个答案:

答案 0 :(得分:0)

按rails惯例重定向的URL正在重定向到索引操作。检查您的日志以查看发生的情况。如果你执行了/ my_objects / index,那么你就知道你想要带有ID = index的my_object。

答案 1 :(得分:0)

您能否发布您的routes.rb,因为您可以指定如何获得这样的路线:

  
    

获取' my_objects / index' => '#my_objects指数'

  

然后在控制器中你只需要做一个

  
    

redirect_to my_objects

  

答案 2 :(得分:0)

在路线中更改此行

get "index" => "my_object#index"

get "index" => "my_object#index", as: :my_object_index

然后重定向到该路径

redirect_to my_object_index_path, notice: "saved successfully"