[英]Problem with polymorphic association in Rails
I am trying to follow Ryan Bates screencast but have an error message. 我正在尝试关注Ryan Bates的截屏视频,但有一条错误消息。 I did the following:
我做了以下工作:
1) Create table 1)创建表
class CreateComments < ActiveRecord::Migration
def self.up
create_table :comments do |t|
t.references :commentable, :polymorphic => true
2) Setup models 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) Change controller show action 3)更改控制器显示动作
class CategoriesController < ApplicationController
def show
@category = Category.find_by_permalink(params[:id])
@commentable = @category
@comment = Comment.new(:commentable => @category)
end
4) Add a form to template views/categories/show.html.erb 4)将表单添加到模板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) After that I get error message by accessing /categories/my-category-permalink 5)之后,我通过访问/ categories / my-category-permalink收到错误消息
NoMethodError in Categories#show
undefined method `category_comments_path' for #<ActionView::Base:0x69a9254>
Could you help me to understand what I did wrong? 您能帮我了解我做错了什么吗? In the original screencast Ryan accesses comments by /categories/permalink/comments using nested associations, but I don't need that.
在原始的屏幕录像中,Ryan使用嵌套关联通过/ categories / permalink / comments访问注释,但我不需要。 I want to write comments directly from my polymorphic objects.
我想直接从多态对象写评论。 Thanks
谢谢
The problem was in routes settings. 问题出在路由设置中。 I thought that since I don't use nested resources, I can keep routes unchanged.
我以为既然不使用嵌套资源,就可以保持路由不变。 Well, now I know that I was wrong... :) Add this to fix the problem:
好吧,现在我知道我错了... :)添加此命令可以解决此问题:
map.resources :categories :has_many => :comments
map.resources :products, :has_many => :comments
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.