Permalinks with Ruby on Rails (dynamic routes)

后端 未结 6 1241
眼角桃花
眼角桃花 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].

    0 讨论(0)
  • 2020-12-09 07:28

    I personally prefer to do it this way:

    Put the following in your Post model (stick it at the bottom before the closing 'end' tag)

    def to_param
      permalink
    end
    
    def permalink
      "#{id}-#{title.parameterize}"
    end
    

    That's it. You don't need to change any of the find_by methods. This gives you URL's of the form "123-title-of-post".

    0 讨论(0)
  • 2020-12-09 07:29

    Modifying the to_param method in the Model indeed is required/convenient, like the others said already:

    def to_param
      pagename.parameterize
    end
    

    But in order to find the posts you also need to change the Controller, since the default Post.find methods searches for ID and not pagename. For the show action you'd need something like this:

    def show
      @post = Post.where(:pagename => params[:id]).first
    end
    

    Same goes for the other action methods.

    You routing rules can stay the same as for regular routes with an ID number.

    0 讨论(0)
  • 2020-12-09 07:40

    The #63 and #117 episodes of railscasts might help you. Also check out the resources there.

    0 讨论(0)
  • 2020-12-09 07:45

    You can use the friendly_id gem. There are no special controller changes required. Simple add an attribute for example slug to your model..for more details check out the github repo of the gem.

    0 讨论(0)
  • 2020-12-09 07:49

    for user-friendly permalinks you can use gem 'has_permalink'. For more details http://haspermalink.org

    0 讨论(0)
提交回复
热议问题