Friendly_Id and reserved words. How to replace a reserved word?

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 a Post model that can replace the new word β€œ-” or something in that direction, but I'm not sure where to start.

Thanks!

+4
source share
3 answers

Using the answers of daemonsy and SizzlePants , I came up with this that calmly renames the β€œnew” to β€œnew2” and β€œedit” to β€œedit2”, and saves 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
source

I just noticed that this is an old question. I'd love to know how you solved the problem.

. 7 RESTFul keywords are blocked as friendly as a bullet choice. The intruder is new here.

From your code, it seems that you are trying to set slug to β€œnew”, since this is the title of your message.

To prevent the use of reserved words, you can force the slug generator to 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 

In this code example, when creating a message called my post , localhost:3000/posts/1-my-post works localhost:3000/posts/1-my-post . Separator - added automatically and can be changed.

See Friendly Id Guide.rdoc for details .

0
source

This is how I got around things. I'm really not sure if this is correct or not ... but I'm using it now. It would be very nice 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 
0
source

Source: https://habr.com/ru/post/1379747/


All Articles