【发布时间】:2015-10-03 17:43:05
【问题描述】:
我正在为我的标签系统使用acts_as_taggable_on,其中每篇文章都有一个或多个标签。然而,它现在的设置方式,标签是大写的,并且在它们之间有空格和特殊字符,这些都会传递给我的路线。换句话说,像“巴拉克奥巴马”这样的标签一直传递到路线不变;看来我的网址完全未编码。
我想知道处理这个问题的正确方法是什么。
我的文章控制器如下所示:
class ArticlesController < ApplicationController
before_action :set_articles, only: [:tagged]
def tagged
@tag = params[:tag]
tagged_with = @articles.tagged_with(@tag)
if @tag.present? && tagged_with.present?
@articles = tagged_with
else
redirect_to root_path, alert: "Oops! There are no articles with tagged #{@tag}"
end
end
private
def set_articles
@articles = user_signed_in? ? Article.all : Article.where published: true
end
end
我的 routes.rb 看起来像这样:
Rails.application.routes.draw do
root 'home#index'
# This is the route that generates publicly facing tag urls:
get 'tags/:tag', to: 'articles#tagged', as: :tag, tag: /.*/
# This is for internal use:
%w(people cities countries other).each do |tag|
get tag, to: "articles#collect_tags", as: tag, tag: tag
end
end
当我点击一个标签时,我的网址目前看起来像:
http://mywebsite.com/tags/Barack Obama
或
http://mywebsite.com/tags/Shinzō Abe
我不确定这些是在内部转义还是需要做些什么?任何建议表示赞赏。
【问题讨论】:
标签: ruby-on-rails routes