diff --git a/app/models/vote.rb b/app/models/vote.rb index 96f987930..82a639993 100644 --- a/app/models/vote.rb +++ b/app/models/vote.rb @@ -7,7 +7,16 @@ class Vote < ApplicationRecord accepts_nested_attributes_for :vote_options, allow_destroy: true - validates :max_choice_vote_options_count, numericality: { greater_than: 0 } + validates :max_choice_vote_options_count, + numericality: { + greater_than: 1, + less_than_or_equal_to: 20, + allow_nil: true + }, + if: :is_multiple_choice? + + validate :validate_multiple_choice_settings + def expired? due_at.present? && due_at < Time.current @@ -53,4 +62,14 @@ class Vote < ApplicationRecord return 0 if total.zero? (option_votes.to_f / total * 100).round(2) end + + def validate_multiple_choice_settings + if is_multiple_choice? && max_choice_vote_options_count.nil? + errors.add(:max_choice_vote_options_count, '多选投票必须设置最大选择数') + end + + if !is_multiple_choice? && max_choice_vote_options_count.present? + errors.add(:max_choice_vote_options_count, '单选投票不需要设置最大选择数') + end + end end