如何在 jQuery 中调用 rails 方法 [英] How to call a rails method from in jQuery
本文介绍了如何在 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").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
这篇关于如何在 jQuery 中调用 rails 方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文