How to create proxy routing for applications for Rails?

I have several different models in the Rails application I'm working on. I saw that on several sites the proxy application routing approach is used. What do I mean by that?

http://example.com/nick-oneill <-- This points to a User object
http://example.com/facebook    <-- This points to a Company object
http://example.com/developers  <-- This points to the users#index page

I know that to_param and create readable bullets in applications, but I do not know how to use bullets at the root level for different objects. You may think that this is similar to the Facebook API: there are different types of objects, but they all exist at https://graph.facebook.com/object-id

Any insight would be greatly appreciated!

+5
source share
3 answers

, freindly_id, , - , .

, , slugs .

Sluggable_type sluggable_id, slug permalink/slug.

+---------------------------------------------+
| sluggable_type | sluggable_id |     slug    |
|      user      |       13     |  users/john |
+---------------------------------------------+

, , , .

routes.rb

  get "/*segments",
               :controller => 'slugs',
               :action => 'dynamicroute'

SlugsController

def dynamicroute
  segments = params[:segments]
  slugs.find_by_slug(segments)
  slug.sluggable_type.constantize.find(slug.sluggable_id) #retrive real record
  #some magic to handle the slugged item maybe redirect to the appropriate
  #controller or somehow call the show view for that controller
end

routes.rb

begin  
  Slug.all.each do |s|
    begin
      get "#{s.slug}" => "#{s.sluggable_type.demodulize.pluralize.camelize}#show"
    rescue
    end
  end
rescue
end

, ,

YOUR_APP_NAME::Application.reload_routes!

, .

, .

+10

, , , , :

  • friendly_id
  • /([-_a-zA-Z0-9]+) - EntitiesController#show
  • /developers, Users#index
  • EntitiesController # show:

    @entity = User.find(params[:id]) or Company.find(params[:id]) or raise ActionController::RoutingError.new('Not Found')

  • , , :

    render "VIEW_PATH_BASED_ON_ENTITY_CLASS/show"

( , , ).

, , , , slug , .

FWIW , ; , .

+2

- Slug. belongs_to:

belongs_to :sluggable, :polymorphic => true

:

  • value - - , . .
  • sluggable_type sluggable_id - .

, .. :

has_one :slug

:

  • slug. , . .
  • , resource . , / , . . - , j_mcnally.
  • All the logic for slug, for example, what a valid slug does is stored in this one model. Good separation of problems, not pollution, says the user model. Especially if the traffic rules are the same for everyone, as they are here.

Regarding the operation of the controller, I would say that Kyle said and canceled the field sluggable_typeto find the view you want to display.

0
source

All Articles