ARTLoe
ARTLoe

Reputation: 1799

Making URL look much neater - Rails 5

I am unsure how to make my url much neater or prettier. could one kindly advise me

i currently have this url:

http://www.example.com/speed-meetings/dine%20with%20index%20venture%20capital

and would like it to look like the below url:

http://www.example.com/speed-meetings/dine-with-index-venture-capital

my route file:

get 'speed-meetings/:title', controller: 'speed_meetings', action: 'show'

views/events/index.html.erb

<td><%= link_to 'show', "/speed-meetings/#{event.title}" %></td>

Upvotes: 0

Views: 75

Answers (2)

max
max

Reputation: 101821

Use the stringex gem:

# Gemfile
gem 'stringex'

# A simple prelude
"simple English".to_url => "simple-english"
"it's nothing at all".to_url => "its-nothing-at-all"
"rock & roll".to_url => "rock-and-roll"

# parameterize will not fare well with these cases:
"$12 worth of Ruby power".parameterize => "12-worth-of-ruby-power" # oops
# Let's show off
"$12 worth of Ruby power".to_url => "12-dollars-worth-of-ruby-power"
"10% off if you act now".to_url => "10-percent-off-if-you-act-now"

# You dont EVEN wanna rely on Iconv for this next part
"kick it en Français".parameterize => "kick-it-en-franais" # oops
"kick it en Français".to_url => "kick-it-en-francais"
"rock it Español style".to_url => "rock-it-espanol-style"
"tell your readers 你好".to_url => "tell-your-readers-ni-hao"

class Thing < ApplicationRecord
  acts_as_url :name

  def to_param
    url
  end
end

Upvotes: 1

Alex Kojin
Alex Kojin

Reputation: 5204

You can use parameterize method to make it prettier.

<%= link_to 'show', "/speed-meetings/#{event.title.parameterize}" %>

Too you can look at 'friendly-id' gem. It's good to work with slugs.

https://gist.github.com/cdmwebs/1209732 - this is great post about friendly urls.

Upvotes: 3

Related Questions