问题
I want to add buttons on my article so that I can know the number of times its clicked and update counter on the database, I am using mongoid ,my model is:
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
My articles show controller is:
def show
@article = Article.find(params[:id])
respond_to do |format|
format.html # show.html.erb
format.json { render :json => @article }
end
end
My View for show is:
<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 %>
I find anything about it in internet.
How can I achieve it?
回答1:
The easiest thing to do would be add a click_count
integer attribute to your Article
model and then increment this in your controller code:
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
回答2:
i got it done, phew!
I added the following form in my 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%>
and wrote the following update controller:
def update
@article=Article.find(params[:id])
if params[:like]
@article.likes=@article.likes+1
elsif params[:dislike]
@article.dislikes=@article.dislikes+1
elsif params[:spam]
@article.spams=@article.spams+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
It worked like a charm.
来源:https://stackoverflow.com/questions/8681355/adding-button-click-counter-in-rails-3