Friday, July 22, 2016

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

Leave a Comment

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 Answers

Answers 1

The redirected URL by rails convention is redirecting to the index action. Check your logs to see what happening. If you do /my_objects/index, you're telling rails you want the my_object with ID = index.

Answers 2

Can you please post your routes.rb because there you can specify how you get a route like this:

get 'my_objects/index' => 'my_objects#index'

and then in the controller you just do a

redirect_to my_objects

Answers 3

In the routes change this line

get "index" => "my_object#index" 

To

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

Then redirect to that path

redirect_to my_object_index_path, notice: "saved successfully" 
If You Enjoyed This, Take 5 Seconds To Share It

0 comments:

Post a Comment