使用Rails 5简单的链接点击计数器,而不使用gem

时间:2021-12-26 15:18:52

I have a post page with a consistent <a href=""> link button in it. I need to show link clicked number for each post. I already have table columns as

我的帖子页面中包含一致的链接按钮。我需要显示每个帖子的链接点击号码。我已经有表格列了

t.integer "count_click"

How can I make this counter in the simplest form possible?

如何以最简单的形式制作此计数器?

<%= link_to @post.reference_title, @post.reference_url, target: :_blank %>

I probably can make it happen with a simple SQL query in the Controller, right? But I have no idea how to trigger it with click

我可能会在Controller中使用简单的SQL查询来实现它,对吧?但我不知道如何通过点击触发它

Thank you!

谢谢!

1 个解决方案

#1


1  

For a basic implementation, as per my comments, I'd do it in the controller action. I guess I would do it all in the same action for your example.

对于基本实现,根据我的评论,我将在控制器操作中执行此操作。我想我会以同样的方式为你的例子做这一切。

For your original question there were 2 counters:

对于您的原始问题,有2个柜台:

t.integer "count_click"
t.integer "count_view"

I'd try to add a param to the link itself that would pass when clicking it:

我试图在链接本身添加一个param,点击它时会传递:

<%= link_to @post.reference_title, reference_url(@post, clicked: true), target: :_blank %>

For a basic implementation you could increment like this:

对于基本实现,您可以像这样增加:

def reference
  # Increment the view counter whenever page loads.
  Post.increment_counter(:count_view, @post.id)
  # Increment the click counter if the link was clicked based on param.
  Post.increment_counter(:count_click, @post.id) if params[:clicked] == "true"
end

#1


1  

For a basic implementation, as per my comments, I'd do it in the controller action. I guess I would do it all in the same action for your example.

对于基本实现,根据我的评论,我将在控制器操作中执行此操作。我想我会以同样的方式为你的例子做这一切。

For your original question there were 2 counters:

对于您的原始问题,有2个柜台:

t.integer "count_click"
t.integer "count_view"

I'd try to add a param to the link itself that would pass when clicking it:

我试图在链接本身添加一个param,点击它时会传递:

<%= link_to @post.reference_title, reference_url(@post, clicked: true), target: :_blank %>

For a basic implementation you could increment like this:

对于基本实现,您可以像这样增加:

def reference
  # Increment the view counter whenever page loads.
  Post.increment_counter(:count_view, @post.id)
  # Increment the click counter if the link was clicked based on param.
  Post.increment_counter(:count_click, @post.id) if params[:clicked] == "true"
end