Reputation: 4474
I have a simple ToDo app with Task model (title:string, due:datetime).
I'm trying to use a before_validation callback to prevent my app from adding (or not validating) empty tasks but have no idea how to achieve that. It's important for me to make it before_validation because there are some validation rules i need to use on my tasks.
So, here i've tried doing this that way:
class Task < ActiveRecord::Base
before_validation :remove_empty_tasks
def remove_empty_tasks
if self.title.empty? && self.due.empty?
self.destroy
end
end
end
But it's not working. All other possible solutions i've found on the internet were not helpfull neither. Can you please give me some advice what is the proper way to do this? Thanks in advance.
Upvotes: 1
Views: 744
Reputation: 54882
You can use the following:
class Task < ActiveRecord::Base
before_validation :remove_empty_tasks
def remove_empty_tasks
if self.title.blank? && self.due.blank?
self.errors.add(:title, 'Should not be empty!')
end
end
end
With this configuration:
Task.create(title: '', due: Date.today)
#=> does not create the task (title is empty)
Task.create(title: 'Bonjour')
#=> does not create the task (due is nil)
Task.create(title: 'Aurevoir', due: Date.today)
#=> passes the custom validation 'remove_empty_tasks'
Upvotes: 2
Reputation: 18530
Why don't you just use validates_presence_of
?
class Task < ActiveRecord::Base
validates_presence_of :title
validates_presence_of :due
end
Upvotes: 1