2009-09-26 126 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