Aimee Fritz
Aimee Fritz

Reputation: 11

Rails Routing: Set specific controller action to a different path

I am looking to set the show action for a controller to a specific path (a path without the controller prefix). I know this can be done by controller by doing this

resources :items, path: ''

But is there a way to do this on only one specific action within the controller?

My end goal is to be able to say www.example.com/my-item-name and take the user to the item without changing the URL. I tried using a catchall route but redirecting adds the prefix back which I do not want.

Any ideas?

Upvotes: 1

Views: 4618

Answers (2)

max
max

Reputation: 101811

You can define single routes manually with the match, get,post, put, macros:

get :bar, to: 'foos#bar'
get :bar, controller: 'foos' # works the same as above
post :bar, to: 'foos#bar'

You can also use scope if you want to route multiple routes to the same controller more elegantly:

scope controller: 'foos' do
  get :bar
  get :baz
end

Upvotes: 1

Tamer Shlash
Tamer Shlash

Reputation: 9523

You can specify which controller and action respond to a certain route in your routes.rb file, like this:

get 'something', to: 'controller_name#action_name'

See Rails Routing Guide.

Upvotes: 3

Related Questions