Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/matlab/13.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby on rails 如何从控制器的每个动作中呈现公共JS?_Ruby On Rails_Action_Render_Commonjs_Respond To - Fatal编程技术网

Ruby on rails 如何从控制器的每个动作中呈现公共JS?

Ruby on rails 如何从控制器的每个动作中呈现公共JS?,ruby-on-rails,action,render,commonjs,respond-to,Ruby On Rails,Action,Render,Commonjs,Respond To,例如,我有一个名为Organizations的controller,它包括基本的CRUD操作和所有的respond\u toJS操作,所以我在controllerrespond\u to:JS的开头写了respond\u to块,{only:%I[index destroy create]}现在要为所有这些操作渲染一个公共JS,即要在所有操作而不是所有特定于操作的JS上渲染index.JS.erb。那么,同样的解决方案是什么呢?您可以通过覆盖提供的default\u render方法来覆盖隐式渲

例如,我有一个名为
Organizations
controller,它包括基本的CRUD操作和所有的
respond\u to
JS操作,所以我在controller
respond\u to:JS的开头写了
respond\u to
块,{only:%I[index destroy create]}
现在要为所有这些操作渲染一个公共JS,即要在所有操作而不是所有特定于操作的JS上渲染
index.JS.erb
。那么,同样的解决方案是什么呢?

您可以通过覆盖提供的
default\u render
方法来覆盖隐式渲染

class OrganizationsController
将响应添加到应用程序中的:jscontroller@RajarshiDas这仍然会隐式地呈现action_name.js.erb。抱歉,没有办法告诉rails隐式地呈现其他视图。这有点违背了约定优于配置的整个目的。您需要明确地告诉rails要
render:index
。在控制器的每个操作中,您可以在respond_to block中使用format.js的
template:
选项来指定要使用的.js.erb文件,例如:
format.js{render template:“someviewsfolder/common.js.erb”}
模板:选项会出现在你的应用程序/视图/文件夹中。我错了。有一种非常简单的方法可以覆盖隐式默认渲染行为。
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