forked from Trustie/forgeplus
18 lines
656 B
Ruby
18 lines
656 B
Ruby
class UserVoteOption < ApplicationRecord
|
|
belongs_to :user
|
|
belongs_to :vote_option, counter_cache: true
|
|
|
|
validates :user_id, uniqueness: { scope: :vote_option_id, message: "您已经投过票了" }
|
|
|
|
private
|
|
def user_can_vote_only_once_per_vote
|
|
return unless user && vote_option
|
|
|
|
existing_vote = UserVoteOption.joins(:vote_option)
|
|
.where(user_id: user_id, vote_options: { vote_id: vote_option.vote_id })
|
|
.where.not(id: id) # 排除自身(更新时)
|
|
.exists?
|
|
errors.add(:base, '您已经投过票了') if existing_vote
|
|
end
|
|
end
|