Johnson
Johnson

Reputation: 1749

Rails - Changing the URL title through Rails Routing

I asked this question on Code Review but they suggested I ask it here

I'm trying to create custom routes for every web page in my show action.

Movie.all.each do |movie|
  match "/#{movie.title.downcase}", to: 'movies#show', via: 'get', 
  as: :"#{movie.title.downcase.gsub(/[:.]/, '').gsub(' ', '_')}"
end

This code matches every web page to my not found page.

resources :movies, except: [:show]

It should match the web page to the actual page.

I only have a show.html.erb file in my views folder. Could that be the problem?

Is it possible to use string interpolation on view file names?

I can't use Rails REST routing because I need to have better URLS.

/Movie Title

is a better URL then

/movies/1

That is why I need to optimize this code. It works, but it could use improvement.

I have no idea how to fix this. Here are a couple things I thought of.

Using Rails route redirection to another action
Using wildcard as view names (*.html.erb)

Remember: My only goal is to change the URL name to the movie's title

Upvotes: 1

Views: 266

Answers (1)

neo
neo

Reputation: 4116

This can be easily achieved using FriendlyId gem

Here's the link:

https://github.com/norman/friendly_id/blob/master/README.md

Add it to your Gemfile

Then add following to your model:

class Movie < ActiveRecord::Base
  extend FriendlyId
  friendly_id :title, use: :slugged

Then run this on rails console:

Movie.find_each(&:save)

To save slugs for existing movies

The documentation is quite good, feel free to comment if you have any trouble.

Upvotes: 4

Related Questions