如何实现“空头”?轨道中嵌套的虚荣网址? [英] How to implement "short" nested vanity urls in rails?

查看:73
本文介绍了如何实现“空头”?轨道中嵌套的虚荣网址?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我了解如何在Rails中创建虚荣网址,以便将
http://mysite.com/forum/1 转换为 http://mysite.com/some-forum-name

I understand how to create a vanity URL in Rails in order to translate http://mysite.com/forum/1 into http://mysite.com/some-forum-name

但是我想更进一步,以下工作(如果可能的话):

But I'd like to take it a step further and get the following working (if it is possible at all):

而不是:
http://mysite.com/forum/ 1 / board / 99 / thread / 321

我希望在第一步中达到以下目的: http://mysite.com/1/99/321

I'd like in the first step to get to something like this: http://mysite.com/1/99/321

并最终使其像 http: //mysite.com/some-forum-name/some-board-name/this-is-the-thread-subject

推荐答案

要在Rails URL助手中很好地完成这项工作,您必须覆盖 to_param 在您的模型中:

To have this work "nicely" with the Rails URL helpers you have to override to_param in your model:

def to_param
  permalink
end

其中永久链接是由 before_save

before_save :set_permalink

def set_permalink
  self.permalink = title.parameterize
end

创建永久链接的原因是,最终,也许,那么您的标题可能不是网址友好的。这就是进入参数化的地方。

The reason you create a permalink is because, eventually, maybe, potentially, you'll have a title that is not URL friendly. That is where parameterize comes in.

现在,关于根据永久链接是您可以走简单路线还是走硬路线。

Now, as for finding those posts based on what permalink is you can either go the easy route or the hard route.

简单路线

定义 to_param 略有不同:

def to_param
  id.to_s + permalink
end

继续使用 Forum.find(params [:id])其中, params [:id] 类似于 1-我很棒的论坛。为什么这仍然有效?好吧,Rails将在传递给 find 的参数上调用 to_i ,然后调用 to_i 只会返回 1

Continue using Forum.find(params[:id]) where params[:id] would be something such as 1-my-awesome-forum. Why does this still work? Well, Rails will call to_i on the argument passed to find, and calling to_i on that string will return simply 1.

硬路线

保留 to_param 相同。求助于在控制器中使用 find_by_permalink ,并使用通过路径传递的 params [:id]

Leave to_param the same. Resort to using find_by_permalink in your controllers, using params[:id] which is passed in form the routes:

Model.find_by_permalink(params[:id])

现在有趣的部分

现在您想从URL中获取资源。嗯,这是西西弗斯式的方法。确保您可以停止使用路由助手Ruby on Rails提供的 map.resources 并使用 map.connect进行定义。 真的值得那么多收益吗?它赋予您什么特别的超能力?

Now you want to take the resource out of the URL. Well, it's a Sisyphean approach. Sure you could stop using the routing helpers Ruby on Rails provides such as map.resources and define them using map.connect but is it really worth that much gain? What "special super powers" does it grant you? None, I'm afraid.

但是仍然,如果您想这样做,这里是一个不错的起点:

But still if you wanted to do that, here's a great place to start from:

get ':forum_id/:board_id/:topic_id', :to => "topics#show", :as => "forum_board_topic"

这篇关于如何实现“空头”?轨道中嵌套的虚荣网址?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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