Note that there are some explanatory texts on larger screens.

plurals
  1. POProblem with polymorphic association in Rails
    primarykey
    data
    text
    <p>I am trying to follow <a href="http://railscasts.com/episodes/154-polymorphic-association" rel="nofollow noreferrer">Ryan Bates screencast</a> but have an error message. I did the following:</p> <p>1) Create table</p> <pre><code>class CreateComments &lt; ActiveRecord::Migration def self.up create_table :comments do |t| t.references :commentable, :polymorphic =&gt; true </code></pre> <p>2) Setup models</p> <pre><code>class Comment &lt; ActiveRecord::Base belongs_to :commentable, :polymorphic =&gt; true class Product &lt; ActiveRecord::Base has_and_belongs_to_many :categories has_many :comments, :as =&gt; :commentable class Category &lt; ActiveRecord::Base has_and_belongs_to_many :products has_many :comments, :as =&gt; :commentable </code></pre> <p>3) Change controller show action</p> <pre><code>class CategoriesController &lt; ApplicationController def show @category = Category.find_by_permalink(params[:id]) @commentable = @category @comment = Comment.new(:commentable =&gt; @category) end </code></pre> <p>4) Add a form to template views/categories/show.html.erb</p> <pre><code>&lt;% form_for [@commentable, Comment.new] do |f| %&gt; &lt;p&gt; &lt;%= f.label :name %&gt;&lt;br /&gt; &lt;%= f.text_field :name %&gt; &lt;/p&gt; &lt;p&gt; &lt;%= f.label :content %&gt;&lt;br /&gt; &lt;%= f.text_area :content %&gt; &lt;/p&gt; &lt;p&gt; &lt;%= f.submit 'Submit' %&gt; &lt;/p&gt; &lt;% end %&gt; </code></pre> <p>5) After that I get error message by accessing /categories/my-category-permalink</p> <pre><code>NoMethodError in Categories#show undefined method `category_comments_path' for #&lt;ActionView::Base:0x69a9254&gt; </code></pre> <p>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. I want to write comments directly from my polymorphic objects. Thanks</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload