如何在控制器的每个操作中呈现通用的JS?

huangapple go评论68阅读模式
英文:

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

问题

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

英文:

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

得分: 0

你可以通过覆盖ActionController::ImplicitRender提供的default_render方法来覆盖隐式渲染。

class OrganizationsController < ApplicationController
  def default_render(*args)
    # 是否存在特定于操作的模板?
    if template_exists?(action_name.to_s, _prefixes, variants: request.variant)
      super
    # 是否存在可用于索引的模板?
    elsif template_exists?('index', _prefixes, variants: request.variant) 
      render :index, *args
    # 我们没有模板。让默认渲染器处理错误
    else 
      super
    end
  end
  # ...
end
英文:

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

huangapple
  • 本文由 发表于 2020年1月3日 21:04:59
  • 转载请务必保留本文链接:https://go.coder-hub.com/59579141.html
  • action
  • commonjs
  • render
  • respond-to
  • ruby-on-rails