2014-09-03 89 views
0

所以我试图记录一个链接被点击的次数,但不能超过最后的障碍。链接被点击的次数

我见到目前为止以下内容:

的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

类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 %> 

首先,这个设置看起来是否正确,没有人看到我可能出错的地方吗? 其次,我不知道如何设置我的视图,以便当点击现有的链接点击注册和计数增加?

感谢

回答

0

用下面的解决了click实例。

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文件。

0

在我看来,你应该做两件事情:

1)将所有的“点击”的方法到模型

例如,你可以删除你的ClicksController并加上:

class Article 
    def create_click(ip_address) 
    self.clicks.create({ :ip_address => ip_address }) 
    end 
end 

这段代码的小记录:你有一个唯一性验证你的c颂。事实上,当文章和IP地址已经存在点击时,create方法将返回false。请勿使用create!,否则会引发异常。

2)添加过滤器:

你可以简单地在你的ArticlesController添加过滤器。在每个show,它会创建为观看article

class ArticlesController 
    before_filter :create_click, :only => [ :show ] 

    def create_click 
    @article.create_click(ip_address) 
    end 
end 
+0

感谢@ForgetTheNorm,我实际上只是通过用'<%= link_to paper_article_views_path(article.id,article),method :: post,target:'_blank'do%>'替换原来的link_to来实现这个工作,但是我仍然得不到的是为什么我需要给路由'article.id'和'文章'?我想通过试验和错误..谢谢 – Robbo 2014-09-03 14:47:18

+0

@James编辑您的原始消息,并分享你的'config/routes',你的路线很奇怪。 – pierallard 2014-09-03 14:51:43

+0

我已经添加了'routes.rb'。你是说路线嵌套的方式是我不得不将'article.id'和'article'放到路线上的原因吗?欢呼声 – Robbo 2014-09-03 15:44:42