Permalinks with Ruby on Rails (dynamic routes)

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

提交回复
热议问题