FriendlyID doesn't build HTML escaped slugs

非 Y 不嫁゛ 提交于 2019-12-12 03:49:12

问题


I have friendly_id setup properly and everything works, using slugs.

The issue I am having is that some of the names on my Tag model (which is the model that FriendlyId is attached to) need to be HTML escaped.

Names like c++ or .net.

When I ran Tag.find_each(:&save), it generated all the slugs for me....but on those tags with those names, this is what happened:

> c = Tag.where(:name => "c++")
  Tag Load (0.9ms)  SELECT "tags".* FROM "tags" WHERE "tags"."name" = 'c++'
 => [#<Tag id: 2, name: "c++", num_questions: 187598, created_at: "2013-03-23 07:02:09", updated_at: "2013-03-29 15:34:09", questions_count: 87, slug: "c">] 
> Tag.where(:name => ".net")
  Tag Load (0.9ms)  SELECT "tags".* FROM "tags" WHERE "tags"."name" = '.net'
 => [#<Tag id: 142, name: ".net", num_questions: 149074, created_at: "2013-03-23 07:09:47", updated_at: "2013-03-29 15:34:10", questions_count: 85, slug: "net">] 
1.9.3p392 :012 > Tag.where(:name => "c#")
  Tag Load (1.0ms)  SELECT "tags".* FROM "tags" WHERE "tags"."name" = 'c#'
 => [#<Tag id: 38, name: "c#", num_questions: 435620, created_at: "2013-03-23 07:03:27", updated_at: "2013-03-29 15:34:10", questions_count: 130, slug: "c--3">] 

Notice the slugs on each of those - and how they don't correspond properly to the name of each record.

How do I fix this?


回答1:


friendly_id (at least when you call it with :use => :slugged) tries to "clean up" the field value so that it will look nice in a URL. If you want to change that behavior, you can override normalize_friendly_id. If you do that, you'll need to be sure to URL-encode your slugs though, because things like # already have special meaning in URLs.

For anyone coming across this later, the working solution was to avoid using friendly_id's :use_slugged, instead just using the raw names of the tags and having them automatically escaped by Rails' link helpers. For the ".net" tag, it also required the routes to be changed to resources :tags, :constraints => { :id => /.*/ } to keep Rails from interpreting the dot as a path separator.



来源:https://stackoverflow.com/questions/15707692/friendlyid-doesnt-build-html-escaped-slugs

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!