级联删除ActiveRecord

时间:2015-11-01 14:30:26

标签: ruby-on-rails activerecord

如何添加一系列删除操作,删除任何已移除的用户的Profile,TodoList和TodoItem行。

用户模型:

class User < ActiveRecord::Base
  has_one :profile
  has_many :todo_lists
  has_many :todo_items, through: :todo_lists, source: :todo_items
  validates :username, presence: true
  end

个人资料模型:

class Profile < ActiveRecord::Base
     belongs_to :user

     validates :first_name, presence: true
     validates :last_name, presence: true

     validates :gender, inclusion: %w(male female)

     validate :first_and_last
     validate :male_Sue


    def first_and_last
      if (first_name.nil? and last_name.nil?)
        errors.add(:base, "Specify a first or a last.")
      end
    end

    def male_Sue
      if (first_name == "Sue" and gender == "male")
        errors.add(:base, "we are prevent male by name Sue.")
      end
    end
  end

TodoList模型:

class TodoList < ActiveRecord::Base

    belongs_to :user
    has_many :todo_items, dependent: :destroy
    default_scope { order :list_due_date }
  end

TodoItem模型:

class TodoItem < ActiveRecord::Base
  belongs_to :todo_list

  default_scope {order :due_date }
end

谢谢,迈克尔。

2 个答案:

答案 0 :(得分:1)

我想添加dependent: :destroy即可。

#user.rb
class User < ActiveRecord::Base
  has_one :profile, dependent: :destroy
  has_many :todo_lists, dependent: :destroy
  has_many :todo_items, through: :todo_lists, source: :todo_items, dependent: :destroy
  validates :username, presence: true
end

答案 1 :(得分:1)

来自文档:

has_manyhas_onebelongs_to关联支持:dependent选项。这允许您指定在删除所有者时删除关联的记录

通过在User类中的关联上使用dependent: :destroy,无论何时销毁用户,该实例的所有关联对象也会被销毁。

您可以check this documentation获取更多信息。