2009-09-26 121 views
0

我正在嘗試關注Ryan Bates screencast,但有錯誤消息。我做了以下內容:Rails中多態關聯的問題

1)創建表

class CreateComments < ActiveRecord::Migration 
    def self.up 
    create_table :comments do |t| 
     t.references :commentable, :polymorphic => true 

2)設置模式

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

class Product < ActiveRecord::Base 
    has_and_belongs_to_many :categories 
    has_many :comments, :as => :commentable 

class Category < ActiveRecord::Base 
    has_and_belongs_to_many :products 
    has_many :comments, :as => :commentable 

3)變更控制器show動作

class CategoriesController < ApplicationController 
    def show 
    @category = Category.find_by_permalink(params[:id]) 
    @commentable = @category 
    @comment = Comment.new(:commentable => @category) 
    end 

4)的形式添加到template views/categories/show.html.erb

<% form_for [@commentable, Comment.new] do |f| %> 
    <p> 
    <%= f.label :name %><br /> 
    <%= f.text_field :name %> 
    </p> 
    <p> 
    <%= f.label :content %><br /> 
    <%= f.text_area :content %> 
    </p> 
    <p> 
    <%= f.submit 'Submit' %> 
    </p> 
<% end %> 

5)之後,我通過訪問/類別/我的類別,永久得到錯誤信息

NoMethodError in Categories#show 
undefined method `category_comments_path' for #<ActionView::Base:0x69a9254> 

你能幫我明白我做錯了什麼? 在原始截屏中,Ryan使用嵌套關聯訪問/ categories/permalink/comments的評論,但我不需要。我想直接從我的多態對象寫評論。 謝謝

+0

在截屏頁面,纈氨酸發佈了一個鏈接到演示代碼他糾正: 59瓦爾8月25日,2009 at 10:02 我修復了所有可以從 下載的bug和工作代碼www.rubyf.info/files/polimorphic_work0.zip – Andrei 2009-09-26 23:13:34

回答

1

問題出在路線設置。我認爲,因爲我不使用嵌套的資源,我可以保持路線不變。好了,現在我知道我錯了...... :)增加這個來解決這個問題:

map.resources :categories :has_many => :comments 
map.resources :products, :has_many => :comments