1
class Tutorial
has_many :comments
end
class VideoTutorial < Tutorial
end
class Comments
belongs_to :tutorial
end
routes.rb
倒像是:
resources :tutorials do
resources :comments
end
我希望能夠參考特定類型的Tutorial
(從VideoTutorial
)所示:
/tutorials/1234
/tutorials/1234/comments/new
/tutorials/1234/comments/6374
這意味着儘可能多地處理教程Tutorial
,而不是VideoTutorial
(或其他子類)。
我想要所有的調用去單個控制器,並使用上面的直接路由。
問題:現在發生的事情
我的形式似乎是多態匹配的路由,滿足特定Tutorial
實例的類型,例如
# @tutorial is a VideoTutorial
= form_for @tutorial do |f| # undefined method 'video_tutorial_path'
...
這是很酷,但不是我在這種情況下:)
我目前做的事情通過生成這些路由工作,尋找:
resources :tutorials do
resources :comments
end
resources :video_tutorials, :controller => "tutorials" do
resources :comments
end
我指揮到Tutorials
控制器,因爲我想避免大量的控制器乘以,當新的Tutorial
子類出現。
但是,這就會變得混亂:
- 當你添加的
Tutorial
- 一個新的子類,你最終會引用PARAMS像
:video_tutorial_id
而不僅僅是你得到了很多額外的路線 - 你得到更多的途徑通用
:id
我想治療所有類型的Tutorial
在日Tutorial
以上情況。
什麼是更簡單,不太麻煩的方法?
UPDATE:按@ JDL的建議
鏈接Tutorial
顯示頁面:
# original approach:
= link_to 'Show', @tutorial
# now:
= link_to 'Show', tutorial_path(@tutorial)
form_for
幫手:
# original approach:
= form_for @tutorial do |f|
# now:
= form_for @tutorial, :as => :tutorial, :url => tutorial_path do |f|
form_for
嵌套的資源:
# original approach:
= form_for [@tutorial, @new_comment] do |f|
# now:
= form_for [@tutorial, @new_comment], :as => :tutorial, :url => tutorial_comments_path(@tutorial, @new_comment) do |f|
現在按預期工作。
有點羅嗦:)任何進一步的想法,讓它更優雅?
感謝@jdl,根據建議的解決方案,我更新了我原來的問題與修訂方法,即現在的工作原理 –