Routing Aliases

I have a model called Spaces that has different types of places ... such as bars, restaurants, etc. She has the same columns, the same model, controller, etc. there is no STI fantasy, I just have a field called Space_type , which I would like to define using aliases.

Instead of domain.com/spaces/12345 it will be /bars/12345 or /clubs/12345

I currently have:

  resources :spaces do collection do get :update_availables get :update_search get :autocomplete end member do post :publish post :scrape end resources :photos do collection do put :sort end end resources :reviews end 

Also, is there a way I can do this to use space_url at any time, can it determine which one to use?

+6
source share
2 answers

Routes are not a way to interact directly with your model. Therefore, while you are writing a standard route, you can make everything work. For example, to make /bars/12345 and /clubs/12345 for your spaces_controller (or any other controller name), you can create routes, for example:

 scope :path => '/bars', :controller => :spaces do get '/:id' => :show_bars, :as => 'bar' end scope :path => '/clubs', :controller => :spaces do get '/:id' => :show_clubs, :as => 'clubs' end 
+6
source
 # routes.rb match "/:space_type/:id", :to => "spaces#show", :as => :space_type # linking link_to "My space", space_type_path(@space.space_type, @space.id) 

which will generate these URLs: /bars/123 , /clubs/1 ... any space_type you have

And it looks like STI wold makes this work a little cleaner;)

UPD

You can also add restrictions to prevent some collisions:

 match "/:space_type/:id", :to => "spaces#show", :as => :space_type, :constraints => { :space_type => /bars|clubs|hotels/ } 

And yes, it’s a good idea to put this route at the bottom of all other routes.

You can also wrap it as an assistant (and rewrite your default space_url ):

 module SpacesHelper def mod_space_url(space, *attrs) # I don't know if you need to pluralize your space_type: space.space_type.pluralize space_type_url(space.space_type, space.id, attrs) end end 
+5
source

Source: https://habr.com/ru/post/885967/


All Articles