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...
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...
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.
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.