如何从jQuery中调用rails方法

我有这个JQuery代码:

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

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

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

此方法在我的用户模型中。 有没有办法做到这一点?

进行AJAX呼叫,设置路由,使用控制器操作进行响应并调用方法。

 # 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:此代码适用于Rails 3.x和Ruby 1.9.x.

拥有该型号代码是件好事。 我们需要添加新操作并确保您的路线已设置完毕。 如果您正在使用资源,则必须添加集合或成员。 由于您正在进行更新,我会选择PUT作为http方法。

这是一个示例路线:

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

继续并将render_read操作添加到控制器。

你的jQuery代码看起来像这样:

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

您需要在服务器端设置一个控制器来调用render_read方法,然后您可以在jQuery中使用$.ajax$.post来发出请求。

通常,JavaScript在客户端工作,但您的应用程序也可能为每个客户端绘制javaScript函数。 在这种情况下,您可以在.erb文件中使用<%=和tags %>