1

I have a Day model which has a date column. I have to implement the validation that the date column must not have a past date. If the date is a past date it must not get saved to the database and give the appropriate error message right on the. I know I can put this validation in the controller, but I think it violates the MVC rules i.e keeping the business logic away from the controllers.

Is there any way to put this validation in the model or anywhere else and if the date is a past date then it must redirect back to the new action with the message "Date cannot be a past date"

Please Help Thanks in advance

3 Answers 3

7

In your model you need add a validation

validate :not_past_date

def not_past_date
  if self.date < Date.today
    errors.add(:date, 'not in past')
  end
end

After in your controller, you just check if save return true or false. False is send when you don't validate your model. If false redirect to another controller.

Edit :

Like said by Simone Carletti in comment you can use #past?

validate :not_past_date

def not_past_date
  if self.date.past?
    errors.add(:date, 'not in past')
  end
end
Sign up to request clarification or add additional context in comments.

4 Comments

You must use Date.today instead of Time.now. we cannot compare date with time downvote for that. but still you showed me the correct way thats why right answer. Please do edit the answer to the correct one
Also, Rohit, you should accept the answer if it is the correct one.
If you are using Rails, you can take advantage of #past? method. Use self.date.past?
@Rohit Don't expect answerers to be psychic. You downvoted for using Date.today, but you didn't include code snippets that make it clear how to answer. "date column" could be common parlance for "datetime column", esp as you didn't include your database provider.
1

I know I can put this validation in the controller, but I think it violates the MVC rules i.e keeping the business logic away from the controllers.

Eeh, in Rails you should put validations in the model (not in the controller!). See: http://guides.rubyonrails.org/active_record_validations_callbacks.html.

Comments

1

@Simone and @shingara using the #past? method will compare a date with the current DateTime in UTC. So you may face a problem in two occasions here:

  1. If you want to get all elements with a DateTime set to a day, wether they began at the beginning of the day or not;

  2. If you are working on another TimeZone.

There are workarounds to deal with it, but it's just more straightforward to do the first @shingara way: self.date < Date.today

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.