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

查看:15
本文介绍了使用 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:

用户应该能够设置页面名称,例如.test-article"(应该可以通过/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

但为了找到帖子,您还需要更改控制器,因为默认的 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

其他操作方法也是如此.

Same goes for the other action methods.

您的路由规则可以与带有 ID 号的常规路由保持相同.

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

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

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