0

For example, I have a controller named Organizations, which includes basic CRUD actions and all the actions respond_to JS, so I wrote the respond_to block at the beginning of the controller respond_to :js, { only: %i[index destroy create] } and now want to render a common JS for all these actions ie want to render index.js.erb on all actions rather than all action specific JS. So What can be the solution for the same?

  • 1
    add respond_to :js in application controller – Rajarshi Das Jan 03 '20 at 13:11
  • 1
    @RajarshiDas that will still implicitly render *action_name*.js.erb. AFAIK there is no way to tell rails to implicitly render some other view. That would kind of defeat the whole purpose of convention over configuration. You need to explicitly tell rails to `render :index`. – max Jan 03 '20 at 14:30
  • In each of your controller actions you could use the `template:` option for format.js in your respond_to block to specify which .js.erb file to use like: `format.js { render template: "someviewsfolder/common.js.erb" }` The template: option looks in your app/views/ folder. – Ben HartLenn Jan 03 '20 at 14:39
  • I was wrong. There is a pretty easy way to override the implicit default rendering behaviour. – max Jan 03 '20 at 14:59

1 Answers1

0

You can override the implicit rendering by overriding the default_render method provided by ActionController::ImplicitRender.

class OrganizationsController < ApplicationController
  def default_render(*args)
    # is there an action specific template?
    if template_exists?(action_name.to_s, _prefixes, variants: request.variant)
      super
    # is there an index template we can use insted?
    elsif template_exists?('index', _prefixes, variants: request.variant) 
      render :index, *args
    # We don't have a template. lets just let the default renderer handle the errors
    else 
      super
    end
  end
  # ...
end
max
  • 96,212
  • 14
  • 104
  • 165