基本要点: 我目前正在尝试创建一个具有向上或向下功能的评级计数器。我创建了一个单独的模型来显示评级计数器,而计数器属于帖子。我试图创建一些Reddit甚至Stackoverflow的东西。我目前仍然坚持做什么。谢谢大家。
数据库:评级表:post_id,user_id,评级
数据库:发布表:ratings_count
评分模型
class Rating < ActiveRecord::Base
attr_accessible :post_id, :user_id, :ratings
has_many :post
has_many :users
validates :post_id, presence: true
validates :user_id, presence: true
end
发布模型
class Post < ActiveRecord::Base
attr_accessible :ratings_count
belongs_to :user
has_many :ratings
validates :user_id, presence: true
validates :smiles, presence: true
end
评级控制器
Nothing in it
后置控制器
class PostsController < ApplicationController
def rate
@post = post.find(params[:id])
if params[:ratings_count]
@post.ratings_count=@post.ratings_count+1
end
end
def unrate
unsure
end
end
评级表
<%=form_for @post, :action=>"rate" do |f|%>
<%= f.hidden_field :ratings_count %>
<%=f.submit "Rate"%>
<%end%>
答案 0 :(得分:0)
您可以使用以下内容: http://ar.rubyonrails.org/classes/ActiveRecord/Base.html#M000348
class PostsController < ApplicationController
def rate
Post.increment_counter(:ratings_count, params[:id]) if params[:ratings_count]
end
def unrate
# You will obviously need to check for a ratings_down or something similar field in your form
Post.decrement_counter(:ratings_count, params[:id]) if params[:ratings_count]
end
end