Home > database >  How to limit creation of polls
How to limit creation of polls

Time:10-07

i have a module where i can create polls, the admin user fills in a form the url of the survey and its expiration date, the goal is that if i already create 1 poll and the expiration date is not yet met do not allow me to create other one.

i run a simple scaffold like this

rails g scaffold poll name url expiration_date:date

thats all i got by now.

validates :poll_existence

    def poll_existence
        if self.expiration_date.present?
            if self.expiration_date >= Date.today
                errors.add(:base, "a message")
            end
        end
    end

I tried with a validates method and its passing the conditions, but its working for all the actions, so it doesnt allow me to create any poll.

CodePudding user response:

If i understand, your validation is if there is already one poll that it`s not expired, the admin cannot create another poll, alright?

If i were you i would do something like that:

  1. Create a scope for ongoing polls:
class Poll < ApplicationRecord
  scope :ongoing , -> { where('expiration_date > ?', Time.zone.now) }
end
  1. For validations:
validates :poll_existence, on: :create

def poll_existence
  if Poll.ongoing.exists?
    errors.add(:base, "Already have a poll")
  end
end

CodePudding user response:

You are not checking other polls from the parent model. Lets' assume the parent model is User

validates :poll_existence

def poll_existence
    if self.expiration_date.present?
        if self.user.polls.where("DATE(expiration_date) > DATE(?)", Date.today).any?
            errors.add(:base, "a message")
        end
    end
end

should work

  • Related