簡體   English   中英

Rails 4 link_to無法生成正確的資源路徑

[英]Rails 4 link_to not generating correct resource path

我有一個資源已設置為在URL中使用:slug而不是:id。

我的rake routes看起來像

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

但是,當我在模板(haml)中執行

= link_to course_type.name, course_type

它鏈接到/courses/1course_type具有id:1slug:"type_a" )。 它不應該指向/courses/type_a嗎?

我也嘗試使用show_course_type_path[:show, course_type]但是它們都引發了undefined method: show_course_type_path

如何獲得導軌以生成正確的路徑?

假設您的資源是CourseType,並且您有一個@course_type實例變量:

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

這應該放在類似:

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

為了將@course_type用作參數,在course.rb中:

def to_param
  name
end

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM