How to create app-wide slug routing for Rails app?

前端 未结 3 1356
清酒与你
清酒与你 2020-12-03 13:07

I have a number of different models in the Rails app I\'m working on. I\'ve seen a number of sites use an app-wide slug routing approach. What do I mean by this?



        
3条回答
  •  长情又很酷
    2020-12-03 13:39

    My first reaction is to create a new Slug model. This model would have a polymorphic belongs_to:

    belongs_to :sluggable, :polymorphic => true
    

    At the least this table would have:

    • value - Or some better name than this. The value of the slug itself.
    • sluggable_type and sluggable_id - The polymorphic foreign keys.

    Your company, user, etc. models models would just have a slug:

    has_one :slug
    

    This gives us a few advantages off the bat:

    • It's now easy to make a unique constraint on the slug value. If the slug were kept as a property of all the different sluggable models, your unique constraint would have to check all the other sluggable tables for uniqueness. Makes for a bad time.
    • The routing is simple enough, since you can use a normal resource route off of the root level namespace. You would want to keep it low/at-the-end of the route file though so other more specific routes take precedence. Edit: This routing is basically the first routing method j_mcnally suggests.
    • All the logic for a slug, like what makes a valid slug, is kept in this one model. Good separation of concerns instead of polluting say a User model. Especially if the slug rules are the same for everyone as they are here.

    In terms of how the controller would work, I'd go with what Kyle said and key off the sluggable_type field to find the view you want to render.

提交回复
热议问题