加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

ruby-on-rails – 如何为每个评论实现每个用户一票?

发布时间:2020-12-17 03:20:30 所属栏目:百科 来源:网络整理
导读:我目前有一个注释控制器,其方法是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
我目前有一个注释控制器,其方法是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

这允许多次投票起伏.我如何设计它,以便用户每条评论只能投票一次,但不知何故,如果他们投票或投票,他们会保持跟踪,这样他们就有能力改变他们的投票.

解决方法

你可以这样做.它禁止相同的投票,但允许将投票改为相反的投票(这是一个竖起大拇指/拇指向下的系统).

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

移民:

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

或者,您可以使用名为thumbs_up或任何其他的gem.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读