Search code examples
ruby-on-railspolymorphic-associations

Using slugs in polymorphic_path


Is there a way I can use parameters in a polymorphic_path, to pass in a slug?

For instance, I have the following routes

routes.rb

MyApp::Application.routes.draw do

  match "movies/:slug" => 'movies#show', :as=>:movie
  match "series/:slug" => 'series#show', :as=>:series

end

And I have the following models:

Movie.rb

class Movie < ActiveRecord::Base
    has_many :cast_members, :as=>:media_item
end

Series.rb

class Series < ActiveRecord::Base
    has_many :cast_members, :as=>:media_item
end

CastMember.rb

class CastMember < ActiveRecord::Base
  belongs_to :media_item, :polymorphic=>true
end

This works great, and I can reference my movie from the cast member, and vice-versa, just like a normal has_many/belongs_to relationship. I can also do this from within my cast_member view:

*cast_members/show.html.erb*

link_to (@cast_member.movie.title, movie_path(@cast_member.movie.slug))

which returns "movie/movie-title"

and I can do

*cast_members/show.html.erb*

link_to (@cast_member.movie.title, polymorphic_path(@cast_member.media_item))

but this returns "/movies/24"

I've tried passing a slug as an item to polymorphic_path in different ways, like

link_to (@cast_member.movie.title, polymorphic_path(@cast_member.media_item, @cast_member.media_item.slug))
link_to (@cast_member.movie.title, polymorphic_path(@cast_member.media_item, :slug=>@cast_member.media_item.slug))
link_to ([@cast_member.movie.title, polymorphic_path(@cast_member.media_item, @cast_member.media_item.slug]))

but these all return errors or the path with the id.

How can I make the polymorphic_path use the movie.slug instead of the id?


Solution

  • I switched over to using friendly_id to generate slugs. It magically handles all the slug<->id conversions magically in the background, and sosolves the issue.

    I do think that rails should have a baked-in way to do this, the same way you can pass a slug into the default *_path methods.