简体   繁体   English

Rails-我可以从ActionCable coffeescript中调用控制器方法吗?

[英]Rails - can I call a controller method from my ActionCable coffeescript?

I'm building a quiz app that leads all participants synchroneously through multiple stages: 我正在构建一个测验应用程序,该应用程序可以在多个阶段同步引导所有参与者:

  1. Phase 0: Quiz has not started 阶段0:测验尚未开始
  2. Phase 1: Current question is being displayed 阶段1:显示当前问题
  3. Phase 3: Result for current question (correct answer vs given answer, statistics etc.) is being displayed 阶段3:显示当前问题的结果(正确答案与给定答案,统计信息等)
  4. Phase 4: Result for entire quiz is being displayed 阶段4:显示整个测验的结果

If a participant loses his connection and reconnects, I want them to be able to immediately pick up where they left off. 如果参与者失去了连接并重新连接,我希望他们能够立即从中断的地方接听。

I always save the current phase to the db. 我总是将当前阶段保存到数据库。 So I'm thinking of calling a method show_current_phase(curent_user) in the connected method of my ActionCable channel. 因此,我正在考虑在我的ActionCable通道的connected方法中调用方法show_current_phase(curent_user) Since I feel like it would make sense to place this method in the corresponding controller for my custom QuizSession model, I'd like to know: 由于我觉得将这种方法放置在自定义QuizSession模型的相应控制器中很有意义,因此我想知道:

Is it possible to call a controller method in my coffeescript (frontend) and have it return an object? 是否可以在我的coffeescript(前端)中调用控制器方法并使它返回一个对象?

Or how do I update the DOM tree of only the user who reconnected without broadcasting to all the other participants? 或者,如何仅更新没有重新广播给所有其他参与者的用户的DOM树?

You can just turning your .coffee file into an .haml or .erb template. 您可以将.coffee文件转换为.haml.erb模板。

.erb example with js .erb示例与js

# myscript.js
var myPath = '/some_path';

Will become 会变成

# myscript.js.erb
var myPath = <%= some_controller_path %> ;

.haml example with coffee .haml咖啡示例

In case you are using haml , the process is not really different. 如果您使用haml ,则过程实际上没有什么不同。

# myscript.coffee
myPath = '/some_path'

Will become 会变成

# myscript.coffee.haml
myPath = '#{ some_controller_path }'

Obviously, you can create .js.haml and .coffee.erb files as well. 显然,您也可以创建.js.haml.coffee.erb文件。

In your case, you could have something like this in your .coffee.haml : 就您而言,您的.coffee.haml可能包含以下.coffee.haml

myFunction = ->
  res = $.ajax(
    url: '#{method_controller_path}'
    method: 'GET'
    data:
      variableParam: '#{@my_controller_var}'
      anotherParam: 'anotherParam'
    dataType: 'json'
    success: (res) ->
      res
  )
  doSomething res

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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