英文:
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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论