Marcus Brunsten
Marcus Brunsten

Reputation: 572

Routing with space replacement in URL

I want to link to /member/:name. I'm using this line in routes.rb:

match 'member/:id', :to => "members#show", :as => :show_member, :via => :get

and this in the model:

def to_param
  username
end

Next, I want to link to a the name represented as a string that has white spaces. I want to replace the white spaces with + (plus) or something else more readable than standard %20 replacement.

I could handle these replacements (from space to +, and from + to space) in a method, but I was wondering if there is a better way of handling this.

Upvotes: 0

Views: 1596

Answers (3)

AndyV
AndyV

Reputation: 3741

You might want to check out the friendly_id gem which was created for this purpose. If you would like to create it yourself then I would consider adding an attribute to the database to store the value by which you will lookup the user. As an idea...

class User < ActiveRecord::Base
  after_create :build_url_parameter
  validates_uniqueness_of :url_parameter, :on => :update

  def to_param
    self.url_parameter
  end

  private
    def build_url_parameter
      self.url_parameter = self.name.gsub(/\s+/, '-')
      unless User.where( url_parameter: self.url_parameter ).count.zero?
        self.url_parameter << "-#{self.id}"
      end
      save
    end
end

By taking this approach you guarantee that the parameter is unique (which may not otherwise be true of users' names).

Upvotes: 1

Mike Campbell
Mike Campbell

Reputation: 7978

@screenmutt is right of course. However, have you tried returning the desired string from to_param? I'm unsure whether it would URL encode the +, but my instinct is that it wouldn't because it's a valid URL character.

def to_param
  username.tr(' ', '+')
end

Then you'd need to write a finder method that converts the + back to a space..

def self.from_param(uname)
  find_by_username!(uname.tr('+', ' '))
end

Upvotes: 3

Dan Grahn
Dan Grahn

Reputation: 9414

Marcus,

This is not something which is standard. Browsers will write %20 for spaces inside of the URL and + for spaces inside of queries.

The only way to convert this would be to do a redirect every time the user searches for a URL with a %20 in it.

However, I don't think this would be worth the effort. Why violate a standard?

When to encode space to plus (+) or %20?

Upvotes: 0

Related Questions