Ruby on rails Rails 4:to_param slug的斜杠是否被转义?
我正在尝试让我的url路径在我的Rails 4.1.7应用程序中看起来像这样:Ruby on rails Rails 4:to_param slug的斜杠是否被转义?,ruby-on-rails,routing,Ruby On Rails,Routing,我正在尝试让我的url路径在我的Rails 4.1.7应用程序中看起来像这样: http://localhost:3000/section/YYYY/MM/DD/article-title-goes-here 为了实现这一点,我创建了一个迁移: rails g migration add_slug_to_articles slug:string:uniq rake db:migrate 然后我在article.rb模型中添加了以下内容: class Article < ActiveRe
http://localhost:3000/section/YYYY/MM/DD/article-title-goes-here
为了实现这一点,我创建了一个迁移:
rails g migration add_slug_to_articles slug:string:uniq
rake db:migrate
然后我在article.rb模型中添加了以下内容:
class Article < ActiveRecord::Base
def to_param
slug
end
end
但是现在当我点击链接时,所有的斜杠都被/转义为%2F:
http://localhost:3000/articles/section%2F2014%2F11%2F10%2Farticle-title-goes-here
我一直在四处寻找,似乎有一个选择是monkeypatch ActionDispatch,但对我来说这似乎有点硬,因为imo非常常见。有没有更干净的方法可以做到这一点?最好为您定义自定义的非restful路由。 指南很好地描述了如何做到这一点: 这种方法将使您能够通过章节、日期和标题过滤文章
另一方面,您当前的方法看起来像是一个黑客。我通过以下方式解决了这个问题:
s = /section1|section2|section3|section4/
y = /\d{4}/
m = /\d{2}/
resources :articles, except: [:index, :show]
resources :articles, only: [:index, :show], path: '/:section/:year/:month', constraints: {:section => s, :year => y, month: m, slug: /[a-zA-Z0-9\-]+/}
get ':section/:year/:month', to: 'articles#by_month', as: :month, constraints: {section: s, year: y, month: m}
get ':section/:year', to: 'articles#by_year', as: :year, constraints: {section: s, year: y}
get ':section', to: 'articles#by_section', as: :section, constraints: {section: s}
那么在我的文章_controller.rb中
def by_section
..
end
def by_year
..
end
def by_month
..
end
def show
@article = Article.find_by_slug params[:slug]
end
唯一真正令人讨厌的是,我需要在视图中的每个路径上传递一组参数:
<%= link_to @article.title, article_path(@article.section, @article.created_at.year, @article.created_at.month, @article.slug, @article.id) %>
对您的无知表示歉意,但我似乎无法理解我是如何按照您所展示的方式设置发送日期的。。。你能解释一下吗?像这样的:获取'articles/:section/:year/:month/:day/:title',到'articles#show'这意味着我总是需要向引用文章的任何链接方法传递5个参数,对吗?你可以定义你自己的助手,我的文章路径(article),在其中你将包含复杂的url生成。在这种情况下,您不会每次都通过所有5个参数
<%= link_to @article.title, article_path(@article.section, @article.created_at.year, @article.created_at.month, @article.slug, @article.id) %>