Rails 新手 - 如何将查询字符串更改为路线
我以大多数人的方式学习 Rails,即通过博客实现。我刚刚添加了标签,并且我的文章视图已达到在您显示文章时显示可点击标签的程度。问题是链接是这样出现的;
http://localhost:3000/articles?tagged_with=development
我不希望有查询字符串,而是有类似的东西;
http://localhost:3000/articles/tagged_with/development
我找不到任何相关内容Rails 网站上的“由内而外的路线”指南(里面有很多有用的东西,但不是这个!)
完整代码如下: https://github.com/mikeyhogarth/mikeyblog
相关位是;
_article.html.erb 中的链接:
<%= link_to tag, articles_path(:tagged_with => tag) %>
文章索引控制器:
def index
if(params[:tagged_with])
@tag = params[:tagged_with]
@articles = Article.tagged_with @tag
else
@articles = Article.all
end
respond_to do |format|
format.html # index.html.erb
format.json { render json: @articles }
end
end
Rails 的最佳实践方法是什么?我是否需要实现“tagged_with”操作并创建一个助手,或者是否有一些 Rails 路由魔法可以快速解决这个问题?
编辑:最终找到了答案
Am learning rails the way most do, by implementing a blog. I've just put tagging in and have got my article view to the point where it's displaying clickable tags when you display an article. The issue is that the links are coming out like this;
http://localhost:3000/articles?tagged_with=development
I would prefer not to have the querystring, and instead have something like;
http://localhost:3000/articles/tagged_with/development
I can't find anything relevant in the "routes inside out" guide on the rails site (lots of useful stuff in there, just not this!)
Complete code here:
https://github.com/mikeyhogarth/mikeyblog
Pertinant bits are;
the link in _article.html.erb:
<%= link_to tag, articles_path(:tagged_with => tag) %>
the articles index controller:
def index
if(params[:tagged_with])
@tag = params[:tagged_with]
@articles = Article.tagged_with @tag
else
@articles = Article.all
end
respond_to do |format|
format.html # index.html.erb
format.json { render json: @articles }
end
end
what is the rails best practice way of doing this? Do I need to implement a "tagged_with" action and create a helper or is there some rails routing magic that can sort this out in a jiffy?
EDIT: Eventually found the answer
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
尝试将类似的内容添加到您的路线中(未经测试):
然后:
Try adding something like this to your routes (untested):
Then:
我最终找到了答案:我需要一条“命名路线”。如果其他人有这个问题,我只是将其放入我的routes.rb 文件中;
然后简单地用这个替换我的“link_to”;
I found the answer eventually: I needed a "named route". If anyone else has this question, I just put this in my routes.rb file;
then simply relpaced my "link_to" with this;