Kev*_*vin 5 ruby-on-rails voting-system ruby-on-rails-3
我目前有一个注释控制器,其方法是vote_up和vote_down,这就是我的vote_up目前的工作方式.
我的评论模型有描述和计数字段.
def vote_up
@comment = Comment.find(params[:comment_id])
@comment.count += 1
if @comment.save
flash[:notice] = "Thank you for voting"
respond_to do |format|
format.html { redirect_to show_question_path(@comment.question) }
format.js
end
else
flash[:notice] = "Error Voting Please Try Again"
redirect_to show_question_path(@comment.question)
end
end
Run Code Online (Sandbox Code Playgroud)
这允许多次投票起伏.我如何设计它,以便用户每条评论只能投票一次,但不知何故,如果他们投票或投票,他们会保持跟踪,这样他们就有能力改变他们的投票.
你可以做这样的事情。它禁止相同的投票,但允许将投票更改为相反的投票(这是一个赞成/反对系统)。
def vote(value, user) # this goes to your model
#find vote for this instance by the given user OR create a new one
vote = votes.where(:user_id => user).first || votes.build(:user_id => user)
if value == :for
vote_value = 1
elsif value == :against
vote_value = -1
end
if vote.value != vote_value
vote.value = vote_value
vote.save
end
end
Run Code Online (Sandbox Code Playgroud)
移民:
def self.up
create_table :votes do |t|
t.references :comment, :null => false
t.references :user, :null => false
t.integer :value, :null => false
end
add_index :votes, :post_id
add_index :votes, :user_id
add_index :votes, [:post_id, :user_id], :unique => true
end
Run Code Online (Sandbox Code Playgroud)
或者,您可以使用名为 或任何其他的 gem thumbs_up。
| 归档时间: |
|
| 查看次数: |
2098 次 |
| 最近记录: |