Rails -FriendlyId 和条件
我有一个模型帖子,属于类别(使用友好 ID)。现在我想列出一个类别中的所有帖子。要获取索引页,我想使用如下链接: http://mysite/posts/category/_category_slug_,为此,我制定了以下路线:
match 'posts/category/:category/' => 'posts#index'
在我的后控制器中,我得到:
def index
if params[:category]
@posts = Post.all(:joins => :category, :conditions => {"categories.cached_slug" => params[:category]})
else
@posts = Post.all.reverse
end
...
它的工作原理应该如此,但我不认为它是 Friedndly_id 的方式。
有更好的方法来实现这一目标吗?感谢您的帮助。
I have a model posts, which belongs_to category (which uses friendly_id). Now i want to list all Posts in an Category. To get the index page i want to use a link like: http://mysite/posts/category/_category_slug_, for that i made the following route:
match 'posts/category/:category/' => 'posts#index'
And in my post controller i got:
def index
if params[:category]
@posts = Post.all(:joins => :category, :conditions => {"categories.cached_slug" => params[:category]})
else
@posts = Post.all.reverse
end
...
It works like it should, but i dont think its the friedndly_id way to do it.
Is there a better way to achive this? thanks for your help.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
FriendlyId 添加了使用 slug 在模型上进行查找的功能,并且足够智能,可以首先检查 cached_slug 列。
您可以通过首先在类别模型上执行查找然后获取所有帖子来获得相同的结果。
这假设存在与引用 ID 列(或 HABTM)的 has_many 和 Belongs_to 关联,
因为您传递的是类别参数(Friendly_id),所以通过类别模型引用它是有意义的。
- 添加了更多信息 -
另外:历史发现仍然有效..
因此,如果您通过重命名类别生成了新的 slug,则旧的 url 将正常运行(如果您要避免 404,那就太好了)
FriendlyId adds the ability to do a find on a model using the slug, and is smart enough to check the cached_slug column first.
You can achieve the same result by performing a find on the Category model first then getting all the posts.
This assumes there is a has_many and belongs_to association in place with the referencing ID columns (or HABTM)
Since you're passing in a category param (being friendly_id), it makes sense to reference it via the Category model.
-- more info added --
ALSO: Historical finds will still work ..
So, if you have generated a new slug by renaming a category, the old url will behave correctly (great if you're avoiding 404's)