首页 > 解决方案 > 如何从控制器的每个动作中渲染一个通用的 JS?

问题描述

例如,我有一个名为的控制器Organizations,其中包括基本的 CRUD 动作和所有动作respond_toJS,所以我respond_to在控制器开头编写了块, respond_to :js, { only: %i[index destroy create] }现在想要为所有这些动作呈现一个通用 JS,即要index.js.erb在所有动作上呈现而不是所有特定于动作的 JS。那么同样的解决方案是什么?

标签: ruby-on-railsactionrendercommonjsrespond-to

解决方案


您可以通过覆盖default_render提供的方法来覆盖隐式呈现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

推荐阅读