问题
Here is an example of what causes the error:
ruby-1.9.2-p290 :004 > Post.new(title: "new").save!
(0.3ms) BEGIN
post Load (0.3ms) SELECT `posts`.* FROM `posts` WHERE (`slug` = 'new' OR `slug` LIKE 'new--%') ORDER BY LENGTH(`slug`) DESC, `slug` DESC LIMIT 1
(0.3ms) SELECT 1 FROM `posts` WHERE `posts`.`lsi_post_id` = BINARY '' LIMIT 1
(0.1ms) ROLLBACK
ActiveRecord::RecordInvalid: Validation failed: Friendly is reserved
I would like to put something in the Post model that maybe replaces a new word with "-" or something along those lines but I'm not sure where to start.
Thank you!
回答1:
Using the answers by daemonsy and SizzlePants I came up with this, which quietly renames "new" to "new2" and "edit" to "edit2", and keeps everything else as before:
class Page < ActiveRecord::Base
extend FriendlyId
friendly_id :friendly_id_title, use: :slugged
def friendly_id_title
case title.parameterize
when 'new' then 'new2'
when 'edit' then 'edit2'
else title
end
end
end
回答2:
I just noticed this is an old question. Would very much like to know how you solved the problem too.
The 7 RESTFul keywords are blocked by Friendly as slug choices. The offender here is new
.
From your code, it seems that you are trying to set the slug to "new" as it is the title of your post.
In order to prevent the reserved words from being used, you can make the slug generator use a method instead of a column.
class Post < ActiveRecord::Base
extend FriendlyId
friendly_id :name_and_id, :use=>:slugged # Used slugged mode, need a slug column in db.
def name_and_id
"#{id}-#{name}"
end
end
From this sample code, when creating a post with the name my post
, going to localhost:3000/posts/1-my-post
works. The -
separator is added automatically and can be changed.
See Friendly Id Guide.rdoc for more details.
回答3:
This is how i got around things.. I'm really not sure if it's right or wrong... but i'm using it for now. Would really love to hear other suggestions.
My application helper looks something like this:
module ApplicationHelper
# Friendly_Id reserved words
def niceify_slug(s)
clean_slug = s
reserved_words = ["new", "edit"]
reserved_words.each { |word| clean_slug = clean_slug.gsub(/\b#{word}\b/i, "#{word}_") }
return clean_slug
end
end
My model looks something like this:
class MyModel < ActiveRecord::Base
include ApplicationHelper
# Slugs via FriendlyId
extend FriendlyId
friendly_id :niceified_name, :use => :slugged
def niceified_name
niceify_slug(self.name)
end
end
来源:https://stackoverflow.com/questions/8017878/friendly-id-and-reserved-words-how-can-i-replace-the-reserved-word