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.
params
variable (it's available in controllers and views only, unless you're passing it to the model, which is probably not what you want).if
checks againstproject.tasks
which 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.if
statement fromif self.tasks
toif self.tasks.any?
which returns the value you want (false
if the array is empty,true
otherwise).check_tasks
method can be changed to the following:code: