计算链接被点击的次数 [英] Count number of times a link is clicked
问题描述
所以我试图记录点击链接的次数,但无法克服最后一个障碍.
So i'm trying to record the number of times a link is clicked but can't get over the last hurdle.
到目前为止,我有以下几点:
I have the following so far:
config/routes.rb
resources :papers do
resources :articles do
resources :clicks
end
end
click.rb
class Click < ActiveRecord::Base
belongs_to :article, counter_cache: true
validates :ip_address, uniqueness: {scope: :article_id}
end
clicks_controller.rb
class ClicksController
应用控制器
class ClicksController < ApplicationController
def create
@article = Article.find(params[:article_id])
@click = @article.clicks.new(ip_address: request.ip)
@click.save
end
end
article.rb
class Article < ActiveRecord::Base
has_many :clicks
end
schema.rb
create_table "clicks", force: true do |t|
t.integer "article_id"
t.string "ip_address"
t.datetime "created_at"
t.datetime "updated_at"
end
create_table "articles", force: true do |t|
t.datetime "created_at"
t.datetime "updated_at"
t.text "title"
t.string "url"
t.integer "paper_id"
t.integer "clicks_count"
end
index.html.erb -- 文章
<% @articles.each do |article| %>
<div class="articles col-md-4">
<%= link_to article.url, target: '_blank' do %>
<h4><%= article.title %></h4>
<h5><%= article.paper.name.upcase %></h5>
<h6><%= article.created_at.strftime("%d %B %y") %></h6>
<% end %>
首先,这个设置看起来是否正确,有没有人看到我哪里出错了?其次,我不知道如何设置我的视图,以便在单击现有链接时点击注册并且计数上升?
Firstly, does this setup look correct, does anyone see where i may have gone wrong? Secondly, what i don't know how to set up my view so that when the existing link is clicked the click is registered and the count goes up?
谢谢
推荐答案
已解决.
clicks_controller.rb
原文:
def create
@article = Article.find(params[:article_id])
@click = @article.clicks.new(ip_address: request.ip)
@click.save
end
end
修正:
def create
@article = Article.find(params[:article_id])
@click = @article.clicks.new(ip_address: request.ip)
@click.save
redirect_to @article.url
end
end
index.html.erb -- 文章
原文:
<%= link_to article.url, target: '_blank' do %>
修正:
<%= link_to paper_article_views_path(article.id, article), method: :post, target: '_blank' do %>
此外,我编辑了原始问题以包含 routes.rb
文件.
Also, i edited the original question to include the routes.rb
file.
这篇关于计算链接被点击的次数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!