如何从rails中的控制器调用javascript函数

时间:2013-05-22 16:46:20

标签: ruby-on-rails

我正在尝试从Rails 3.2应用程序中的控制器调用javascript函数(实际上是coffeescript)。

我收到Render and/or redirect were called multiple times in this action错误。

我的代码如下所示:

#Model.controller

def index
  @models = Model.all
  my_action if current_user.name == "Bob" #or some other general conditional
  ...and some stuff
  respond_to do |format|
    format.html
    format.js #this is needed to handle ajaxified pagination
  end
end

def my_action
  respond_to do |format|
    format.js { render :js => "my_function();" } #this is the second time format.js has been called in this controller! 
  end
end


#functions.js.coffee.erb

window.my_function = ->
  i = xy
  return something_amazing

从控制器调用js函数的正确方法是什么?

1 个答案:

答案 0 :(得分:13)

伙计,你错过了阻止的争论。主要错误。

def my_action
  #respond_to do # This line should be
  respond_to do |format|
    format.js { render :js => "my_function();" }
  end
end

MrYoshiji的观点是正确的。但是你的错误是在服务器端,还没有到达客户端。

对于样式,我认为如果js代码只是一个函数调用就可以了。如果有更多JS代码,最好渲染js模板

 # controller
 format.js

 # app/views/my_controller/my_action.js.erb
 my_function();
 // and some more functions.

更新:如何修复双重渲染问题

如果满足条件,则必须返回#index,否则方法将继续执行并导致渲染两次或更多次。修复如下:

def index
  @models = Model.all
  if current_user.name == "Bob"
    return my_action
  else
    # ...and some stuff
    respond_to do |format|
      format.html
      format.js #this is needed to handle ajaxified pagination
  end
end