rails 单击 link 时的额外操作

rails extra action when clicking on link

我有一个带通知功能的 rails 应用程序。通知具有 :checked_at datetime 属性。在通知索引页面上,我 link 每个通知对象都像 <%= link_to posts_path(anchor: "post_#{notification.notifiable_id}") do %>.

我想要实现的是,当单击此 link(进入可通知对象)时,notification.checked_at attribute 将得到更新。

我有一些不同的解决方案,比如点击 link 时额外的 AJAX 调用,或者有一个额外的路由,比如 notifications#check_notification link 助手会指向并检查属性后它将 redirect_to 原始 posts#index 页面。

我不确定 rails 中哪一种是首选方式(也许是第三种)。 sby 能告诉我该怎么做吗?

您可以向 route 添加另一个参数,例如 update_checked_at,然后在控制器内的 index 操作中检查它是否存在并且它是 true.

<%= link_to posts_path(
  anchor: "post_#{notification.notifiable_id}", 
  update_checked_at: true) do %>

def index
  if params[:update_checked_at]
    # Do your thing