views:

31

answers:

2

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

+1  A: 

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.

captaintokyo
+1  A: 

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
shingara
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
Rohit
Also, Rohit, you should accept the answer if it is the correct one.
Mr. Matt
@Mr.Matt done that :D
Rohit
If you are using Rails, you can take advantage of `#past?` method. Use `self.date.past?`
Simone Carletti
Thanks @Simone even #past? works fine for me. :D
Rohit