Shawabawa
Shawabawa

Reputation: 2597

Rails 4 link_to not generating correct resource path

I have a resource that I have set up to use :slug instead of :id in the url.

My rake routes looks like

     Prefix Verb URI Pattern              Controller#Action
       root GET /                        home#index
       home GET /                        home#index
course_type GET /courses/:slug(.:format) course_type#show

However, in my template(haml) when I do

= link_to course_type.name, course_type

It links to /courses/1 (course_type has id:1 and slug:"type_a"). Shouldn't it point to /courses/type_a?

I also tried using show_course_type_path and [:show, course_type] but they both raised undefined method: show_course_type_path

How can I get rails to generate the correct path?

Upvotes: 0

Views: 442

Answers (1)

a-b-r-o-w-n
a-b-r-o-w-n

Reputation: 515

Assuming your resource is CourseType and you have a @course_type instance variable:

link_to @course_type.name, course_type_path(@course_type.name)

This should out put something like:

<a href="/courses/course-name">course-name</a>

In order to use @course_type as the param, in course.rb:

def to_param
  name
end

Upvotes: 1

Related Questions