Permalinks with Ruby on Rails (dynamic routes)

后端 未结 6 1247
眼角桃花
眼角桃花 2020-12-09 07:14

I am currently developing a blogging system with Ruby on Rails and want the user to define his \"permalinks\" for static pages or blog posts, meaning:

the user shoul

6条回答
  •  庸人自扰
    2020-12-09 07:26

    You should have seolink or permalink attribute in pages' or posts' objects. Then you'd just use to_param method for your post or page model that would return that attribute.

    to_param method is used in *_path methods when you pass them an object.

    So if your post has title "foo bar" and seolink "baz-quux", you define a to_param method in model like this:

    def to_param
      seolink
    end
    

    Then when you do something like post_path(@post) you'll get the /posts/baz-quux or any other relevant url that you have configured in config/routes.rb file (my example applies to resourceful urls). In the show action of your controller you'll just have to find_by_seolink instead of find[_by_id].

提交回复
热议问题