计算单击链接的次数
所以我试图记录链接被点击但无法克服最后一道障碍的次数。
到目前为止我有以下内容:
配置/ 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 <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 – 文章
首先,这个设置看起来是否正确,有人看到我可能出错的地方吗? 其次,我不知道如何设置我的视图,以便在点击现有链接时注册点击并且计数上升?
谢谢
解决了以下问题。
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
文件。
在我看来,你应该做两件事:
1)将“点击”的所有方法设置为模型
例如,您可以删除ClicksController
并添加以下内容:
class Article def create_click(ip_address) self.clicks.create({ :ip_address => ip_address }) end end
这段代码的一点注意事项:您的代码中有唯一性validation。 实际上,当文章和IP地址已经存在点击时, create
方法将返回false。 不要使用create!
相反,它会引发exception。
2)添加filter:
您只需在ArticlesController
添加一个filter即可。 在每个show
,它将为所查看的article
创建一个click
实例
class ArticlesController before_filter :create_click, :only => [ :show ] def create_click @article.create_click(ip_address) end end