Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>It's kind of difficult to wrap your head around it because you don't know what kind of object you're going to be receiving in the comments controller.</p> <p>It's much simpler when it's not a polymorphic relationship. Before we understand how to do that, we need to understand the best way to do the singular version.</p> <p>I should note that this assumes that you have your resources/routes defined correctly:</p> <p>map.resources :posts, :has_many => [ :comments ] map.resources :pages, :has_many => [ :comments ]</p> <p>Let's say that we have the simple example of a Post has many Comments. Here is a sample way of doing this:</p> <pre><code>class CommentsController &lt; ApplicationController before_filter =&gt; :fetch_post def create @comment = @post.comments.new(params[:comment]) if @comment.save success_message_here redirect post_path(@post) else error_message_here redirect_to post_path(@post) end end protected def fetch_post @post = Post.find(params[:post_id]) end end </code></pre> <p>Now we want to use this in a polymorphic relationship, so we have to setup a couple of things. Let's say that we have Pages and Posts that have comments now. Here is a sample way of doing this:</p> <p>From you Posts and Pages show pages:</p> <pre><code>&lt;%= render 'comments/new' %&gt; </code></pre> <p>In the posts controller:</p> <pre><code>before_filter :fetch_post def show @comment = @commentable.comments.build end protected def fetch_post @post = @commentable = Post.find(params[:id]) end </code></pre> <p>This sets up your form to be simple: &lt;% error_messsages_for :comment %></p> <pre><code>&lt;% form_for [ @commentable, @comment ] do |f| %&gt; #Your form fields here (DO NOT include commentable_type and or commentable_id also don't include editor and creator id's here either. They will created in the controller.) &lt;% end %&gt; </code></pre> <p>In your comments controller:</p> <pre><code>def create @commentable = find_commentable # Not sure what the relationship between the base parent and the creator and editor are so I'm going to merge in params in a hacky way @comment = @commentable.comments.build(params[:comment]).merge({:creator =&gt; current_user, :editor =&gt; current_user}) if @comment.save success message here redirect_to url_for(@commentable) else failure message here render :controller =&gt; @commentable.class.downcase.pluralize, :action =&gt; :show end end protected def find_commentable params.each do |name, value| if name =~ /(.+)_id$/ return $1.classify.constantize.find(value) end end nil end </code></pre>
 

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