如何从jQuery中调用rails方法 [英] How to call a rails method from in jQuery

查看:165
本文介绍了如何从jQuery中调用rails方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个JQuery代码:

I have this JQuery code:

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

    });

,我想从jQuery代码里面调用这个rails方法作为回调:

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?

推荐答案

进行AJAX呼叫,设置路由,响应控制器动作和调用你的方法。

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

# whatever.js
$("p.exclamation, div#notification_box").live("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:这段代码适用于Rails 3.x和Ruby 1.9 .x

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

这篇关于如何从jQuery中调用rails方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆