is it possible to call a rails helper method from

2019-07-21 06:06发布

问题:

I have a javascript code block in my application.html.erb [view file] which receives an event from external api. all i want to do is when the event is recieved in the javascript code block i need to execute a helper method inside [application_helper.rb].

I have gone through most of te stacks in here but could not find any relevant answer.

the javascript code block looks like this:

var pusher = new Pusher('b00c9657a0a896f3ec26');
var channel = pusher.subscribe('NewOrders');
channel.bind('NewOrderArrived', function(data) {

    [ I NEED TO CALL THE RAILS HELPER METHOD HERE ]

console.log("got u")
});

回答1:

Not directly, no. As Dave Newton said in the comment, Ruby executes on the server and JS executes on the client. What you'll want to do is something like this:

var pusher = new Pusher('b00c9657a0a896f3ec26');
var channel = pusher.subscribe('NewOrders');
channel.bind('NewOrderArrived', function(data) {
  $.get('<%= url_for :some_controller_method_that_calls_helper %>', function(response){
    // the response variable will contain the output of the controller method
  });
  console.log("got u")
});