views:

63

answers:

4

Hi,

How can i replace " " and "_" with "-" in my controller when creating a new post?

I have the following form fields: title url content

I want to execute the gsub on the url field.

Thanks...

A: 

title.gsub(" ","-").gsub("_","-")

Anubhaw
A: 

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

jpartogi
How do I set it up in my controller action?
A: 

If you're trying to slug the title, then you may find Norman's friendly_id of some use:

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. It'll also integrate with ActiveRecord to override the find methods.

Mr. Matt
@Mr. Matt thanks I got it working and it was just what I was looking for!
A: 

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. <>'"/\.

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.

gertas
@gertas thanks for the info!