title: finding parent in rails polymorphic association
body: <p>I am working on implementing polymorphic comments (these can be applied to just about any user content on the site, and is not limited to <code>Article</code> instances. When creating a comment, I need to determine which <code>commentable</code> it belongs to. Most of the writing I have found on this subject suggests that I use the pattern specified in <code>find_commentable</code> in the code below, but this approach does not strike me as very elegant - it would seem there should be a straightforward way to unambiguously specify the <code>commentable</code> a new comment is being created for, without traversing the <code>params</code> set, and without string matching. Is there a better way?</p>
  
  <p>In other words, is there a better way to access the <code>commentable</code> object from the <code>comment</code> controller in the context of a <code>commentable</code> &rarr; <code>comment</code> association? Does it still work the <code>create</code> method where we do not yet have a <code>@comment</code> object to work with?</p>
  
  <p>My models are set up as follows:</p>
  
  <pre><code>class Comment &lt; ActiveRecord::Base
    belongs_to :commentable, :polymorphic =&gt; true
  end
  
  class Article &lt; ActiveRecord::Base
    has_many :comments, :as =&gt; :commentable, dependent: :destroy
  end
  
  class CommentsController &lt; ApplicationController 
    def create
      @commentable = find_commentable  
      @comment = @commentable.comments.build(comment_params)
  
      if @comment.save
        redirect_to :back
      else  
        render :action =&gt; 'new'
      end  
    end
  
    def index
      @commentable = find_commentable
      @comments = @commentable.comments
    end
  
    private
      def comment_params
        params.require(:comment).permit(:body)
      end
  
      def find_commentable
        params.each do |name, value|
          if name =~ /(.+)_id$/
            return $1.classify.constantize.find(value)
          end
      end
    end
  end
  </code></pre>
  
  <p>Thank you!</p>