开发者

rails routing aliases

I have a model called Spaces which has different types of places... such as Bars, Restaurants, etc. It has the same columns, same, model, controller, etc. no fancy STI, I just have one field called Space_type which I would like to deter开发者_高级运维mine an aliased route.

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

Currently I 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 so that anytime I use the space_url it can figure out which one to use?


The routes are not a way to interact with your model directly. So, as long as you write a standard route, you can make things work. For instance, to make /bars/12345 and /clubs/12345 for your spaces_controller (or whatever the name of the controller is) , you can create routes like :

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  


# 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 this urls: /bars/123, /clubs/1 ... any space_type you have

And it looks like STI wold do this job little cleaner ;)

UPD

Also you can add constraints to prevent some collisions:

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

And yes - it is good idea to put this rout in the bottom of all other routes

You can also wrap it as a helper (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
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜