2

你好,我有一个 Rails 应用程序,它是一个使用设计、ahoy 和优点的封闭社区。

我们有一个叫做资源的脚手架。每个资源都有一个链接

用户模型

class User < ApplicationRecord
  has_merit
  has_many :visits, class_name: “Ahoy::Visit”
end

资源模型

class Resource < ApplicationRecord
  has_rich_text :description
  belongs_to :category
end

控制器

我想使用 Ahoy 跟踪点击链接的用户,以便我可以为访问奖励积分。

看法

<table>
  <thead>
    <tr>
      <th>Title</th>
      <th>Link</th>
      <th>Category</th>
      <th colspan="3"></th>
    </tr>
  </thead>

  <tbody>
    <% @resources.each do |resource| %>
      <tr>
        <td><%= resource.title %></td>
        <td><%= link_to "Learn More", resource.link, class: 'btn btn-dark btn-sm' %></td>
        <td><%= resource.category.name %></td>
        <td><%= link_to 'Show', resource %></td>
        <td><%= link_to 'Edit', edit_resource_path(resource) %></td>
        <td><%= link_to 'Destroy', resource, method: :delete, data: { confirm: 'Are you sure?' } %></td>
      </tr>
    <% end %>
  </tbody>
</table>

架构

create_table "resources", force: :cascade do |t|
    t.string "title"
    t.string "link"
    t.bigint "category_id", null: false
    t.datetime "created_at", precision: 6, null: false
    t.datetime "updated_at", precision: 6, null: false
    t.index ["category_id"], name: "index_resources_on_category_id"
  end

路线

Rails.application.routes.draw do
  resources :visits
  resources :resources
devise_for :users, controllers: { registrations: 'registrations' }
end

我将如何跟踪链接点击并分配积分?

4

2 回答 2

3

让我们在单击链接时向visits_controller 发出请求。config/routes.rb 资源:访问

控制器/visits.rb

class VisitsController < ApplicationController
    def create
        Ahoy::Visit.track('click', link_id: params[:resource_id])
    end
end

我假设 ahoy.authenticate(user) 写在某处让我们将类资源添加到链接和链接 id 作为数据属性,以便我们可以将 ajax 调用绑定到携带必要数据视图的访问控制器

<td><%= link_to "Learn More", resource.link, class: 'resource btn btn-dark btn-sm' data: {resource_id: resource.id} %></td>

资产/javascripts/tracker.js

(document).on('turbolinks:load', function() { #or whatever you used to do in your app
    $('a.resource').on('click', function() {
         that = this
         $.ajax({
             url: 'visits',
             method: 'POST',
             data: {resource_id: $(that).data('resource_id')}
         })
    })
})
于 2019-06-09T01:31:59.723 回答
2

我没有使用 ahoy,所以也许我的帮助可能没有用。

我不是 100% 你需要这样做,我认为可以通过单击资源模型上的文件来实现,每次用户单击链接时都会更新。

我会尝试什么:

在 Resource_controller.rb :

def link
  ahoy.track "Link clicked" if params[:clicked]
  @resource = Resource.find(params[:id])
end

鉴于:

<%= link_to "Learn More", resource_link_path(link: resource.link, clicked: true) resource.link, class: 'btn btn-dark btn-sm' %>

如果您找到另一个解决方案,请在下面发布您的解决方案!

于 2019-06-09T01:16:05.093 回答