我正在尝试调用此post方法,然后重定向到链接所在的位置,但我正在被路由绊倒。该方法被调用,但就是这样。我做错了什么?
<%= link_to image_tag('notifications3.fw.png', size: "32x32", title: "Notifications", class: 'cr'), activities_path %>
我的路线
resources :activities, path: 'notifications'
post 'activities/read_all_notifications'
js
$(document).on('click', '.cr', function(e) {
e.preventDefault();
return $.ajax('/activities/read_all_notifications', {
type: "post",
dataType: "json",
beforeSend: function(xhr) {
return xhr.setRequestHeader("X-CSRF-Token", $("meta[name=\"csrf-token\"]").attr("content"));
},
cache: false
});
});
方法
def index
@activities = PublicActivity::Activity.order(created_at: :desc)
.where(recipient_id: current_user.id,
recipient_type: 'User')
end
def read_all_notifications
PublicActivity::Activity.where(recipient_id: current_user.id).update_all(:read => true)
render nothing: true
end
日志
Started POST "/activities/read_all_notifications" for 127.0.0.1 at 2015-10-19 11:55:51 -0700
Processing by ActivitiesController#read_all_notifications as JSON
User Load (1.0ms) SELECT "users".* FROM "users" WHERE "users"."id" = 3 LIMIT 1
SQL (1.5ms) UPDATE "activities" SET "read" = 't' WHERE "activities"."recipient_id" = 3
Rendered text template (1.5ms)
Completed 200 OK in 28ms (Views: 3.5ms | ActiveRecord: 2.5ms)
答案 0 :(得分:1)
如何更改链接
<%= link_to image_tag('notifications3.fw.png', size: "32x32", title: "Notifications", class: 'cr'), 'activities/read_all_notifications', method: :post %>
并在html中处理它(删除javascript)
# And in the controller
def read_all_notifications
PublicActivity::Activity.where(recipient_id: current_user.id).update_all(:read => true)
redirect_to :activities
end
注意,您可以将路线更改为
resources :activities, path: 'notifications' do
collection do
post :read_all
end
end
然后,在视图中,您可以使用方法(read_all_notifications_path
)来生成网址。从长远来看,这更灵活,更好。
<%= link_to image_tag('notifications3.fw.png', size: "32x32", title: "Notifications", class: 'cr'), read_all_notifications_path, method: :post %>