5

こんにちは、プロジェクトがあり、各プロジェクトにはタスクがあります。タスクはプロジェクトに属します。プロジェクトを削除する前に、関連するタスクがあるかどうかを確認したいと考えています。プロジェクトを削除したくないタスクがある場合。関連するタスクがない場合は、プロジェクトを削除する必要があります。コードを教えてください。私は何が欠けていますか?

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
4

3 に答える 3

6

インスタンスが破棄されないように、before_destroy メソッドからfalseを返します。

このメソッドは、トラブルシューティングのために意味のあるエラーも返す必要があります。

class Project < ActiveRecord::Base
  before_destroy :check_tasks

  def check_tasks
    if self.tasks.any?
      errors.add_to_base "Project has tasks and cannot be destroyed."
      return false
    end
  end
end

注: flash[:notice] と params[:attr_name] はコントローラーからのみ使用できます。

于 2011-11-17T16:58:32.697 に答える
2

ここにはいくつかの問題があります。

  1. You don't (or shouldn't) have access to the 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).
  2. Your if checks against project.tasks which is an array - even an empty array evaluates to true, so your other code branch will never occur no matter if the project has tasks or not.
  3. You should probably be setting error messages for the view from your ProjectsController#destroy action, not in your model.

Solutions:

  1. Change Project.find(params[:id]) to self - you want to check the tasks for every instance of the Project.
  2. Change the check in your if statement from if self.tasks to if self.tasks.any? which returns the value you want (false if the array is empty, true otherwise).
  3. Move the flash[:notice] from your model to your controller, as well as the redirect_to call, where they belong. This means your check_tasks method can be changed to the following:

code:

def check_tasks
  return !self.tasks.any?
end
于 2011-11-17T17:40:58.637 に答える
1

チェックは代わりにセルフにする必要がありますか?(params[:id] をどこから取得したかわかりません)。

ただし、これはまだチェックしていませんが、Users モデルに同様のものが必要なので、それがどのように機能するかを確認して、返信します。

class Project < ActiveRecord::Base  
 before_destroy :check_tasks

 private

 def check_tasks
   #edited 
   if tasks.empty?  
     false
   end 
 end
于 2011-11-17T16:55:42.943 に答える