Rails

How To Change The View Path Of A Controller In Rails

Posted by Weston Ganger on September 15, 2016

Sometimes you may want to change the view path of a controller. Here are two examples that can be used separately or together.


Shared views for multiple controllers: These controllers will both use the view path app/views/posts:


class UserPostsController
  def self.controller_path
    "posts" # change path from app/views/user_posts to app/views/posts
  end
end

class PostsController
   ...
end


Different views paths for different sites:


# app/controllers/application_controller.rb
class ApplicationController < ActionController::Base
  before_action :set_view_path

  private

  def set_view_path
    case request.host
    when "mysite.com"
      site = "my_site" # root view path will be app/views/my_site
    when "myothersite.com"
      site = "my_other_site" # root view path will be app/views/my_other_site
    else
      site = "default_site" # root view path will be app/views/default_site
    end
    prepend_view_path "#{Rails.root}/app/views/#{site}"
  end
end


Related External Links:


Posted in Rails and Tagged with rails 


Need help on your next project or application?

I specialize in Ruby-on-Rails, AngularJS, Javascript, Bootstrap, and Hybrid Mobile Apps with Cordova & Ionic.

Contact Me

Recommended Posts