Route concern and polymorphic model: how to share controller and views?

polymorphic-associations, rails-activerecord, ruby-on-rails, ruby-on-rails-4

Solution

You can find the parent in a before filter like this:

comments_controller.rb

before_filter: find_parent

def find_parent
  params.each do |name, value|
    if name =~ /(.+)_id$/
      @parent = $1.classify.constantize.find(value)
    end
  end
end

Now you can redirect or do whatever you please depending on the parent type.

For example in a view:

= simple_form_for [@parent, comment] do |form|

Or in a controller

comments_controller.rb

redirect_to @parent # redirect to the show page of the commentable.

Problem

Given the routes: ``` Example::Application.routes.draw do concern :commentable do resources :comments end resources :articles, concerns: :commentable resources :forums do resources :forum_topics, concerns: :commentable end end ``` And the model: ``` class Comment < ActiveRecord::Base belongs_to :commentable, polymorphic: true end ``` When I edit or add a comment, I need to go back to the "commentable" object. I have the following issues, though: 1) The `redirect_to` in the `comments_controller.rb` would be different depending on the parent object 2) The references on the views would differ as well ``` = simple_form_for comment do |form| ``` Is there a practical way to share views and controllers for this `comment` resource?

Original source