簡體   English   中英

Rails中的多態關聯問題

[英]Problem with polymorphic association in Rails

我正在嘗試關注Ryan Bates的截屏視頻,但有一條錯誤消息。 我做了以下工作:

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)更改控制器顯示動作

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

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)之后,我通過訪問/ categories / my-category-permalink收到錯誤消息

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

您能幫我了解我做錯了什么嗎? 在原始的屏幕錄像中,Ryan使用嵌套關聯通過/ categories / permalink / comments訪問注釋,但我不需要。 我想直接從多態對象寫評論。 謝謝

問題出在路由設置中。 我以為既然不使用嵌套資源,就可以保持路由不變。 好吧,現在我知道我錯了... :)添加此命令可以解決此問題:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM