Click here to Skip to main content
15,888,286 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
I have two models.

models/Resident.rb : has_many: leaves

models/leave.rb: belongs_to: resident

Now what I want to validate leave model attributes before they get created..

leave.rb attributes : start_date,end_date,destination

here is my leave model:
C#
class Leave < ActiveRecord::Base
  belongs_to :resident
  validates :destination,presence:true
  validates :end_date,presence: true
  validates :start_date,presence: true
  before_create :check_correct_leave

  private

  def check_correct_leave

   if resident.hostel.hostel=='J'
     (self.end_date - self.start_date).to_i == 4 ||  (self.end_date - self.start_date).to_i == 5

   else
     errors.add(:start_date, "Leave are granted only 4 or 5 days")
   end

  end

end

I want check_correct_leave method to also check if the resident already have a leave (stored in a leave model) of that a month (month means jan,feb,etc) then it should generate an error that:

You cant mark leave cause you have already marked leave for this month and model should not store that leave.
Thanks

What I have tried:

I tried this
def has_leave_for_the_same_month?
resident.leaves.any? do |other_leave|
other_leave.start_date.month == leave.start_date.month
end
end

errors.add(...) if has_leave_for_the_same_month?
not working
Posted
Updated 6-Apr-16 20:35pm
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900