2015-11-01 54 views
0

如何添加级联删除将删除任何用户的配置文件,TodoList和TodoItem行删除。级联的删除ActiveRecord

用户模型:

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 

谢谢,迈克尔。

回答

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 
+0

谢谢,它的工作! –

1

从文档:

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

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

您可以通过check this documentation了解更多信息。