Insomania Insomania - 1 year ago 58
Ruby Question

Where to add shared view files in Rails 5?

I am using Rails 5 and I want to use shared files in my project. I have googled about this, and i got some results as follow:

For Rails 3


For Rails 4


but there was nothing for Rails 5,

I am talking about the standard, means is there any specific location to add common view files in Rails 5, just as we do in other frameworks, like in Laravel there is a layout folder,

Please help me to use the correct path to load shared templates.


Answer Source

All the people telling you that there is no "standard location" for common view files are correct. However, if you want to ask Rails where it would go looking for a partial file if you attempted to render one on the view, just take any view file you have and render a partial you know doesn't exist.

If you have, say, a UsersController with a view structure that looks something like app/view/users, and you add the following on any view there:

<%= render 'foo' %>

You'll likely get an error that says something like:

Missing partial users/_foo, application/_foo

That means that whenever you attempt to render a partial by just it's name without any path information, Rails will look for it

  • first under the view directory for the current controller, in this case users
  • then under the application directory

So, I guess then you could say that the "default location" in Rails for common view files is under the application directory.

It's possible to add to this in order to create your app's own "standard location" for common view files by overriding the ActionView::ViewPaths.local_prefixes private class method that gets mixed in to every controller in Rails:

class ApplicationController < ActionController::Base
  def self.local_prefixes
    ['shared', controller_path]
  private_class_method :local_prefixes

class UsersController < ApplicationController
  def self.local_prefixes
  private_class_method :local_prefixes

Now, your error will say something like:

Missing partial users/_foo, shared/_foo, application/_foo

which shows that Rails will check the shared directory for partials as well before it goes looking in the application directory.

Note that this method override should happen in both the controllers, otherwise the local_prefixes in UsersController get inherited from ApplicationController and you end up with duplicated lookup paths that look like:

shared/_foo, users/_foo, shared/_foo, application/_foo

If all this is too much effort/too weird, as other people have pointed out, you can always just specify your shared partial directory manually when you render a partial:

<%= render 'shared/foo' %>