简体   繁体   中英

How to render a common JS from every action of controller?

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM