依赖::destroy不适用于has_one关系

时间:2019-06-20 07:03:17

标签: ruby-on-rails ruby

如果我删除子记录,那么父记录不会自动删除。

class User < ActiveRecord::Base
    has_one :agency, dependent: :destroy
    accepts_nested_attributes_for :agency 
end

class Agency < ActiveRecord::Base
    belongs_to :user
    accepts_nested_attributes_for :user
end

if @agency.present?
   @agency.user.destroy
   flash[:notice] = 'Agency Deleted'                  
end

销毁子记录,以便父记录自动销毁。

2 个答案:

答案 0 :(得分:0)

我认为,可以像这样重写您的模型以获得预期的输出。

class User < ActiveRecord::Base
    has_one :agency # Change
    accepts_nested_attributes_for :agency 
end

class Agency < ActiveRecord::Base
    belongs_to :user, dependent: :destroy # Change
    accepts_nested_attributes_for :user
end

if @agency.present?
   @agency.destroy # Change
   flash[:notice] = 'Agency Deleted'                  
end

现在让我们进行逻辑思考。

您所做的更改是,您使User依赖于Agency,现在可以通过导轨建立父子关系以获得可接受的输出了。因此,销毁@agency时,它还将删除相关的user记录。

答案 1 :(得分:0)

您应使用以下代码删除用户及其关联的代理商,而不对模型进行任何更改。

class User < ActiveRecord::Base
    has_one :agency, dependent: :destroy
    accepts_nested_attributes_for :agency 
end

class Agency < ActiveRecord::Base
    belongs_to :user
    accepts_nested_attributes_for :user
end

if @agency.present?
   user = @agency.user #Change
   user.destroy # This will destroy both user and associated agency.
   flash[:notice] = 'Agency and User Deleted'                  
end

可以在here.上找到有关dependent: :destroy的完整官方指南