Search code examples
ruby-on-railsruby-on-rails-2

Rails 2 - How to Use a Different Layout for an entire sub-site but still be able to use existing Controllers and Models


I am using Rails version 2.3.14 and I am trying to figure out the best way to use a different layout for an entirely new section of my site but I can't think of the most efficient way to do it.

e.g. I have a CRM and everything is localhost/controller/method as normal but what I want to do is create a sub-section of my site named portal.

I considered creating a new app but I don't really want to do that since this sub section will be using existing controllers so I don't want to end up in the situation of having to remember to update both controllers to make sure their contents are identical as that will end up getting messy.

I read this answer rails 3, how add a view that does not use same layout as rest of app? and it makes sense but I can't think how to apply that to my situation.

e.g. http://localhost/ would show my existing login page and something like localhost/portal would show the login page for the new section but with a completely different layout but using the same models and controllers.

I'm new to rails so I might be over-thinking it or I might be barking up the wrong tree.

If it's possible I think the easiest way would be to somehow check the url for portal and set the layout based on the outcome of that check.


Solution

  • I read the answer you posted, it makes sense, I just try to give you some real codes in your case.

    You have a sub site, it means that your path of all pages in sub site will start with '/portal', right?

    In your app/views/layout , you can add a layout named "portal_subsite.html.erb".

    In your application_controller.rb

    class ApplicationController < ActionController::Base
      layout :get_layout
    
      private
    
      def get_layout
        if  request.path.start_with?('/portal')
          'portal_subsite'
        else
          'application'
        end
      end
    end
    

    I have not a environment of Rails 2 now, but I think it should work, if you have any questions, please comment below.