Reputation: 93
Hi I am doing an application for world cup. And in the model I want add a validation: A single team can not play two games on the same date. The date is the field mathdate and the teams are local_team_id and visiting_team_id.I tried with How could I do that validation in the model?
class Match < ActiveRecord::Base
validates :mathdate, :presence => true
validate :mydate_is_date?
validates :stage, :presence => true
validates :stage, numericality: {only_integer: true, greater_than_or_equal_to: 1, less_than_or_equal_to: 6}
validates :state, :presence => true
validates :state, numericality: {only_integer: true, greater_than_or_equal_to: 1, less_than_or_equal_to: 3}
validates :local_team_id, :presence => true
validates :visiting_team_id, :presence => true
validates :stadium_id, :presence => true
def mydate_is_date?
errors.add(:contructiondate, 'must be a valid date') if !mathdate.is_a?(Date)
end
end
Upvotes: 1
Views: 58
Reputation: 3895
Use following validation
validates :local_team_id, presence: true, uniqueness: {scope: :mathdate}
validates :visiting_team_id, presence: true, uniqueness: {scope: :mathdate}
Upvotes: 1