5

私は現在、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

これにより、複数の賛成票と反対票が可能になります。ユーザーがコメントごとに 1 回だけ投票できるように設計するにはどうすればよいでしょうか。

4

3 に答える 3

3

このようなことができます。同一の投票は禁止されていますが、投票を反対に変更することは許可されています (これは、賛成/反対のシステムです)。

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あるいは、またはその他の宝石を使用することもできます。

于 2011-07-21T15:20:40.713 に答える
2
class AnswersController < ApplicationsController
  def vote
    #params[:answer_id][:vote]
    #it can be "1" or "-1"
    @answer = Answer.find(params[:answer_id])
    @answer.vote!(params[:answer_id][:vote])
  end

  def show
    @answer = Answer.find(params[:answer_id])
    @answer.votes.total_sum
  end

end

class Answer < ActiveRecord::Base
  has_many :votes do
    def total_sum
      votes.sum(:vote)
    end
  end


  def vote!(t)
    self.votes.create(:vote => t.to_i)
  end

end

class Vote < ActiveRecord::Base
  belongs_to :answer
  belongs_to :user

  validates_uniqueness_of :user_id, :scope => :answer_id
end
于 2011-07-21T13:37:59.577 に答える
1

おそらく、モデルに検証を追加して、カウントが数値的に1以下であることを確認できます

validates :count, :numericality => { :less_than_or_equal_to => 1 }
于 2011-07-21T13:37:27.147 に答える