Hi I have a project and each project has tasks. A task belongs to a project. Before I delete a project I want to check if there are related tasks. If there are tasks I don't want to delete the project. If there are no associated tasks, the project should be deleted. Can you please help me with the code? What am I missing?
class Project < ActiveRecord::Base
before_destroy :check_tasks
def check_tasks
if Project.find(params[:id]).tasks
flash[:notice] = 'This project has tasks.'
redirect_to :action => 'list_projects'
end
end
end
You have a couple of problems here.
paramsvariable (it's available in controllers and views only, unless you're passing it to the model, which is probably not what you want).ifchecks againstproject.taskswhich is an array - even an empty array evaluates totrue, so your other code branch will never occur no matter if the project has tasks or not.Solutions:
Project.find(params[:id])toself- you want to check the tasks for every instance of the Project.ifstatement fromif self.taskstoif self.tasks.any?which returns the value you want (falseif the array is empty,trueotherwise).check_tasksmethod can be changed to the following:code: