Ruby on Rails的永久链接(动态路由) [英] Permalinks with Ruby on Rails (dynamic routes)

查看:82
本文介绍了Ruby on Rails的永久链接(动态路由)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在使用Ruby on Rails开发博客系统,希望用户为静态页面或博客帖子定义其永久链接,即:

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:

用户应该能够设置页面名称,例如测试文章(应该可以通过/ posts / test-article获得)-如何在Rails应用程序和路由文件中实现这一点?

the user should be able to set the page name, eg. "test-article" (that should be available via /posts/test-article) - how would I realize this in the rails applications and the routing file?

推荐答案

确实需要/方便地修改模型中的 to_param 方法,就像其他人已经说过的那样:

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

def to_param
  pagename.parameterize
end

但是要查找帖子,您还需要更改Controller,因为默认的 Post.find 方法搜索ID而不是页面名称。对于显示动作,您需要这样的东西:

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

其他操作方法。

您的路由规则可以与具有ID号的常规路由相同。

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

这篇关于Ruby on Rails的永久链接(动态路由)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆