我有这个 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 调用、设置路由、响应 Controller 操作并调用您的方法。
# 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 - 如何在 jQuery 中调用 Rails 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5933261/