Peter Tretiakov
Peter Tretiakov

Reputation: 3410

Friendly URL in link_to

I have PointPage model with url field in it. I need to format links to point_page#show on website to:

domain.com/:url

So, I've add to routes.rb

get ':url', to: 'point_pages#show'

And to point_page.rb

def to_param
  url
end

show method in point_page_controller.rb is:

def show
  @point_page = PointPage.find_by(url: params[:url])
end

So, everything works, and domain.com/:url == domain.com/point_pages/:url

But link_to method in views generate urls of second type, not the first one:

link_to 'Link', point_page_path(page) #=> <a href="/point_pages/url">Link</a>

And I need <a href="/url">Link</a>

Thanks for the help!

Upvotes: 0

Views: 63

Answers (1)

infused
infused

Reputation: 24347

Add an as option to the route definition:

get ':url', to: 'point_pages#show', as: 'url'

This will create an url_path route helper:

link_to 'Link', url_path(page)

Upvotes: 2

Related Questions