Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to call javascript functions from the controller in rails

I'm trying to call a javascript function (actually coffeescript) from a controller in a Rails 3.2 app.

I'm getting a Render and/or redirect were called multiple times in this action error.

My code looks like this:

#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 a js function from the controller?

like image 272
Andy Harvey Avatar asked May 22 '13 16:05

Andy Harvey


1 Answers

Man, you missed argument for block. Primary mistake.

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

And MrYoshiji's point is right. But your error was on server side, had not reached client side yet.

For the style, I think that's okay if the js code is one function call only. If more JS code, it's better to render js template

 # controller
 format.js

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

Update: How to fix double rendering problem

You must have your #index return if condition met, or the method will continue to execute and cause 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
like image 161
Billy Chan Avatar answered Oct 13 '22 06:10

Billy Chan