Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
539 views
in Technique[技术] by (71.8m points)

friendly id - Add @ to friendly_id slug Ruby on Rails

I am having a problem adding the @ symbol to slug in my Rails application.

Here is the code from the user model:

validates_format_of :username, with: /^[a-zA-Z0-9_.](?!w*__w*)w+$/, multiline: true

extend FriendlyId
friendly_id :custom_slug, use: :slugged

## Friendly_id: change slug if user's username updated or slug is blank
def should_generate_new_friendly_id?
  slug.blank? && username_changed?
end

## Friendly_id: add @ to slug
def custom_slug
  "@#{username}"
end

It works fine with any other string, but for some reason, it doesn't allow me to add @ in front of the slug. The initial idea is to get a nice URL for each user, for example, www.website.com/@username

Is there any way to allow friendly_id to add the @ symbol?

PS: If you think that it's a bad idea, I would love to know that too.

question from:https://stackoverflow.com/questions/65893671/add-to-friendly-id-slug-ruby-on-rails

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The @ character is a reserved character in URLs, meaning it has a special meaning. If you want to use it as a simple part of the URL without the special meaning, it must be percent encoded first. See https://www.ietf.org/rfc/rfc3986.txt sections 2.1 and 2.2


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...