2011-04-20 56 views
4

我一直在學習Rails大約6周,所以仍然是noob!Rails 3,Polymorphic Associations和No Route Matches

我下面就多態關聯瑞恩·貝茨截屏,但導航到/模型/ XX /評論時,我得到一個「無路由匹配」的錯誤。

經過兩天的研究,我完全陷入了困境 - 一切似乎都已到位。

評論型號:

create_table "comments", :force => true do |t| 
t.text  "content" 
t.integer "user_id" 
t.integer "commentable_id" 
t.string "commentable_type" 
t.datetime "created_at" 
t.datetime "updated_at" 
end 

評論類:

class Comment < ActiveRecord::Base 
belongs_to :commentable, :polymorphic => true 
end 

其他型號等級:

class ModelName < ActiveRecord::Base 
has_many :comments, :as => :commentable 
end 

的routes.rb

resources :modelname, :has_many => :comments 

comments_controller.rb

def index 
@commentable = find_commentable 
@comments = @commentable.comments 
end 

private 

    def find_commentable 
    params.each do |name, value| 
     if name =~ /(.+)_id$/ 
      return $1.classify.constantize.find(value) 
     end 
    end 
    nil 
    end 

這一切都根據教程,但仍然將返回「無路由匹配」。

我已經嘗試了路線的替代格式作爲嵌套資源。

resources :modelname do |modelname| 
    modelname.resources :comments 
end 

在術語的routes.rb中

resources :comments 

及其各種組合顯式定義的評論在routes.rb中

resources :modelname, :has_many => :commentables 

resources :modelname, :has_many => :comments 

resources :modelname, :has_many => :comments, :through => :commentable 

均無功而返。

有沒有其他人遇到過這個?我迷失在哪裏開始尋找。

非常感謝

回答

4

如果您使用的是Rails 3,則路由的處理方式會有所不同。您在模型中指定關係並將路線映射到routes.rb

在Rails 3的處事方式中,您的路線。rb你應該有這樣的:

resources :model do 
    resources :comments 
end 

你不應該在路線中指定你的關係。刷新你的服務器,你應該得到像/ model/id/comments/id這樣的路由

+0

謝謝你讓我擺脫不幸。簡單但有效! – 2011-04-20 04:34:03

+0

我還想補充一點,我添加了一個嵌套的路線,並有相同的問題。然後,我重新啓動服務器,並開始工作。所以基本上,在運行的服務器上添加嵌套路由並不總是可行。 :-)重新啓動它。 – cbmeeks 2011-07-14 23:49:41

3

在Rails 3中,情況有點不同。要獲得URL modelname/id/comments,你會想在你的routes.rb以下路線:

resources :modelname do 
    resources :comments 
end 

this Rails Guide更多,但它去了很多更詳細。

+0

當你知道如何時,很容易!感謝指針和有用的鏈接,像魅力一樣工作。 – 2011-04-20 04:32:35

+0

哈哈,這是它總是工作的方式,是吧?很高興有幫助。 – 2011-04-20 04:39:25