2011-12-30 111 views
2

我想加上我的文章的按鈕,這樣我可以知道的數據庫上的點擊,更新計數器,我使用mongoid的次數,我的模型是:添加按鈕,點擊計數器3

class Article 
    include Mongoid::Document 
    include Mongoid::Timestamps 
    field :title, :type => String 
    field :content, :type => String 
    field :likes, :type => Integer ,:default => 0 
    field :dislikes, :type =>Integer, :default => 0 
    field :spam, :type => Integer, :default => 0 
end 

我的文章顯示控制器:

def show 
    @article = Article.find(params[:id]) 

    respond_to do |format| 
     format.html # show.html.erb 
     format.json { render :json => @article } 
    end 
    end 

我對錶演的看法是:

<p id="notice"><%= notice %></p> 

<p> 
    <b>Title:</b> 
    <%= @article.title %> 
</p> 

<p> 
    <b>Content:</b> 
    <%= raw @article.content %> 
</p> 

Likes : <%= @article.likes %> <br/> 
Dislikes : <%= @article.dislikes %><br/> 
Spams : <%= @article.spam %><br/> 


<%= link_to 'Edit', edit_article_path(@article) %> | 
<%= link_to 'Back', articles_path %> 

我覺得任何事情它在互聯網上。

我該如何實現它?

回答

4

做將是一個click_count整數屬性添加到您的Article模型,然後在你的控制器代碼增加最簡單的事情:

def show 
    @article = Article.find(params[:id]) 
    @article.increment! :click_count 

    respond_to do |format| 
    format.html # show.html.erb 
    format.json { render :json => @article } 
    end 
end 
0

我把它做了,唷!

我說我show.html.erb以下形式:

<%=form_for(@article,:action=>"update") do |f| %> 
<%= submit_tag "Like", :name=>"like"%> 
<%= submit_tag "Dislike",:name=>"dislike"%> 
<%= submit_tag "Spam",:name=>"spam" %> 
<%end%> 

,並寫了下面的更新控制器:

def update 
    @article=Article.find(params[:id]) 
    if params[:like] 
     @[email protected]+1 
    elsif params[:dislike] 
     @[email protected]+1 
    elsif params[:spam] 
     @[email protected]+1 
    end 
    respond_to do |format| 
     if @article.update_attributes(params[:article]) 
     format.html {redirect_to @article, :notice => "Article Updated"} 
     else 
     format.html {render :action=>"edit", :notice=> "Unable to update Article , sorry! :("} 
     end 
    end 
    end 

它的工作就像一個魅力。