user730569
user730569

Reputation: 4004

How to call a rails method from in jQuery

I have this JQuery code:

$("p.exclamation, div#notification_box").live("mouseover", function() {

    });

and I want to call this rails method from inside the jQuery code as a callback:

def render_read
  self.user_notifications.where(:read => false).each do |n|
    n.read = true
    n.save
  end
end

This method is in my user model. Is there any way to do this?

Upvotes: 21

Views: 27603

Answers (4)

edgerunner
edgerunner

Reputation: 14973

Make an AJAX call, set up a route, respond with a controller action and call your method.

# whatever.js
$("p.exclamation, div#notification_box").on("mouseover", function() {
  $.ajax("/users/render_read")
});

# routes.rb
resources :users do
  get :render_read, on: :collection 
  # or you may prefer to call this route on: :member
end

# users_controller.rb
def render_read
  @current_user.render_read
  # I made this part up, do whatever necessary to find the needed user here
end

PS: This code is for Rails 3.x and Ruby 1.9.x

Upvotes: 36

Javier Giovannini
Javier Giovannini

Reputation: 2352

Normally JavaScript works in the client side, but it's is also possible that your application draws a javaScript function for a each client. In that case you can use the <%= and tags %> in a .erb file:

<script type="text/javascript">
$(function(){
    new AClass.function({
        text: <%= Date.today %>
    });
});
</script>

Upvotes: 1

Andy Gaskell
Andy Gaskell

Reputation: 31761

It's good that you have that model code. We'll need to add a new action and make sure your route is setup. If you're using resources you'll have to add collection or member. Since you're doing an update I would choose PUT as the http method.

Here's an example route:

resources :user_notifications do
  collection do
    put 'render_read'
  end
end

Go ahead and add the render_read action to your controller.

Your jQuery code will look something like this:

$("p.exclamation, div#notification_box").live("mouseover", function() {   
  $.ajax({
    url: "/user_notifications/render_read",
    type: 'PUT'
  });
});

Upvotes: 4

mu is too short
mu is too short

Reputation: 434775

You would need to set up a controller on the server side to call your render_read method and then you could use $.ajax or $.post in your jQuery to make the request.

Upvotes: 1

Related Questions