Search code examples
ruby-on-railsviewnested-resources

Different views when nesting resources in Rails


I am using Rails 3.2.1.

Is it possible to use different views when using nested resources? i.e. profile/comments post/comments. Let's say you want both pages to look completely different. Is there a way to do this without overriding render in every controller action?

Preferably I still want to use respond_with.


Solution

  • I didn't find anything, and in the end I did it the following way:

    class NestedController < ApplicationController
    
      before_filter :retrieve_parent
      before_filter :retrieve_scope
    
      layout :retrieve_layout
    
      def retrieve_scope
        @scope = @parent.nil? ? controller_name : @parent.class.name.pluralize.downcase || ''
      end
    
      def retrieve_view
        controller_name + '/' + @scope + '/' + action_name
      end
    
      def retrieve_parent
        params.each do |name, value|
          if name =~ /(.+)_id$/
            @parent = $1.classify.constantize.find(value)
          end
        end
      end
    
      def retrieve_layout
       template_exists?(@scope, 'layouts') ? @scope : 'application'
      end
    
    end
    

    Every controller that uses nested resources, will extend from NestedController.

    Note that the retrieve_parent function has been derived from Ryan's railscast about polymorphic associations.

    Hope this helps someone.