How to call javascript functions from controller in rails

I am trying to call a javascript function (actually coffeescript) from a controller in a Rails 3.2 application.

I get the error Render and/or redirect were called multiple times in this action .

My code is as follows:

 #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 

What is the correct way to call js function from controller?

+7
source share
1 answer

Man, you missed the argument for the block. Primary error.

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

And the point of Mr. Yoshiji is true. But your error was on the server side, has not yet reached the client side.

For style, I think that everything is fine if the js code is just one function call. If there is more JS code, it is better to display the js template

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

Update : how to fix the dual rendering problem

You must have a returned #index if the condition is met, or the method will continue to execute and call rendering twice or more. Fix it like this:

 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 
+12
source

All Articles