Rails 远程 link 更新记录,同时打开 link

Rails remote link update record that also opens the link

我的应用程序包含一个属于客户端模型的引用模型。每个引文只是客户在某个第三方目录上的本地企业列表,例如 yellowpages.com。

所以在我的客户端显示视图中,我有属于该客户端的所有列表,您可以单击 "view listing" link 打开该列表的 url :

<%= @citations.each do |c| %>
  <%= link_to "View Listing", c.listing_url, target: '_blank' %>
<% end %>

单击 link 时,我想使用 ajax 在控制器中调用一个方法来更新该记录的 "updated_at" 列,在打开 link。我可以使用内置远程方法来做到这一点吗?还是我必须编写自己的 javascript 事件侦听器?

为了实现您所要求的确切行为,我建议编写您自己的 javascript 事件侦听器。但是,这是一种具有几乎相同效果的替代方法。它使用 ajax 链接来访问您的控制器,但新的浏览器选项卡只有在您的 Rails 应用响应后才会打开。

将您的链接更改为如下内容:

<%= @citations.each do |c| %>
  <%= link_to "View Listing", {:controller => :citations, :action => :my_action, :citation_id => c.id}, :remote => :true %>
<% end %>

在您的控制器中,加载引文并触摸一下:

class CitationsController < ApplicationController
  def my_action
    @citation = Citation.find( params.require(:citation_id) )
    @citation.touch # updates the updated_at column
  end
end

在响应视图中,my_action.js.erb,在新浏览器中打开 listing_url tab/window:

// same effect as a link with target = _blank
window.open("<%= j @citation.listing_url %>");