简体   繁体   English

导轨gsub问题

[英]rails gsub question

How can i replace " " and "_" with "-" in my controller when creating a new post? 创建新帖子时,如何在控制器中将“”和“ _”替换为“-”?

I have the following form fields: title url content 我有以下表单字段:标题url内容

I want to execute the gsub on the url field. 我想在网址字段上执行gsub。

Thanks... 谢谢...

Remember that getting rid of space and "_" from URL is not enough as there are some other characters which my break your HTML code and even cause script injection. 请记住,仅通过URL除去空格和“ _”是不够的,因为还有其他一些字符会破坏您的HTML代码,甚至导致脚本注入。 <>'"/\\ . <>'"/\\

I suggest passing all letters and numbers - everything else translate to - . 我建议传递所有字母和数字-其他所有内容都转换为-

class Post < ActiveRecord::Base
  attr_protected :url
  validates_presence_of :title
  before_create :generate_url 

  private
    def generate_url
      self.url = title.strip.downcase.gsub(/[^a-z0-9]+/,'-')
    end
end

Controller is unchanged. 控制器不变。

title.gsub(“”,“-”)。gsub(“ _”,“-”)

title.gsub(/[\\s_]+/, '-').strip

If you're trying to slug the title, then you may find Norman's friendly_id of some use: 如果您尝试使用标题,那么您可能会发现Norman的friendly_id有用:

http://github.com/norman/friendly_id http://github.com/norman/friendly_id

It'll take care of creating permalinks for you, so you won't need to worry about duplication or generation of the url in your app. 它会为您创建永久链接,因此您无需担心应用程序中URL的重复或生成。 It'll also integrate with ActiveRecord to override the find methods. 它还将与ActiveRecord集成以覆盖find方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM