0
votes

I have a comments scaffold and a movies scaffold.

Users can comment on movie in this path /movies/the-social-network/comments/new

My issue is that the comments use movie_id to work and to link with the movies.

So what I'm asking is how to pass the-social-network as the movie_id?

PS: Im using Friendly Id 4

2

2 Answers

1
votes

First, since you want to look up Movie by "slug" like the-social-network, you need to extend FriendlyId and tell it to parameterize the id into an attribute called slug. Do this by passing :slugged as follows:

# app/models/movie.rb
class Movie < ActiveRecord::Base
    extend FriendlyId
    friendly_id :title, use: :slugged
end

Then, create a migration to store slug for Movie objects:

# in console
rails g migration add_slug_to_movies slug:string

Modify the migration file to add slug as an index:

# change migration file
class AddSlugToMovies < ActiveRecord::Migration
    def change
        add_column :movies, :slug, :string
        add_index :movies, :slug
    end
end

Finally, you need to create a slug for all the existing movies in your database. You can do this by saving each movie one-by-one:

# in Rails console 
Movie.find_each(&:save)

After you'd done this, you should be able to make lookups on Movie akin to /movies/the-social-network/comments/new.

Check out this Railscast for additional details and examples, including ensuring that an object's slug is correctly update when the title is changed in the database.

0
votes

You can use to_param. For example, if movie_name is 'the-social-network', this will work:

class Movie < ActiveRecord::Base
  def to_param
    movie_name
  end
end