我想在我的文章上添加按钮,以便我可以知道其点击次数并更新数据库上的计数器,我使用的是 mongoid ,我的模型是:
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
我的文章显示 Controller 是:
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 %>
我在互联网上找到了有关它的任何信息。
我怎样才能实现它?
最佳答案
最简单的方法是将 click_count
整数属性添加到您的 Article
模型中,然后在 Controller 代码中增加该属性:
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
关于model-view-controller - 在 Rails 3 中添加按钮点击计数器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8681355/