我有以下情况
class Company < ActiveRecord::Base
has_many :depots, inverse_of: :company, :dependent => :destroy
has_many :users, inverse_of: :company, :dependent => :destroy
has_many :products
end
class Depot < ActiveRecord::Base
has_many :products, :dependent => :destroy
has_many :zones, :dependent => :destroy
belongs_to :company
end
class Product < ActiveRecord::Base
belongs_to :depot
belongs_to :company
end
class Zone < ActiveRecord::Base
belongs_to :depot
end
class User < ActiveRecord::Base
belongs_to :company, , inverse_of: :users
end
## and zone has_many locations which further has some associated models.
我想删除所有与公司相关的模型,而不是逐个调用它们。 我的依赖销毁不起作用,当我试图删除该公司时,产品仍在那里。我试过替换
dependent: :destroy #to delete_all
但没有运气。如何通过单次调用destroy to company删除所有嵌套对象?
我可以打电话
Company.reflect_on_all_associations(:has_many)
并逐个删除所有关联,但我不想采用这种方法。任何帮助?
答案 0 :(得分:0)
I believe using the "inverse_of" clause in your models is the problem as per the last point in the rails docs on it. Remove them and give it a try. As listed in the docs:
There are a few limitations to inverse_of support:
They do not work with :through associations. They do not work with :polymorphic associations. They do not work with :as associations. **For belongs_to associations, has_many inverse associations are ignored.
答案 1 :(得分:0)
不确定您的设置无效,但如果您使inverse_of
对称,则可行:
class Company < ActiveRecord::Base
has_many :depots, inverse_of: :company, dependent: :destroy
has_many :users, inverse_of: :company, dependent: :destroy
has_many :products
end
class Depot < ActiveRecord::Base
has_many :products, inverse_of: :depot, dependent: :destroy
has_many :zones, inverse_of: :depot, dependent: :destroy
belongs_to :company, inverse_of: :depots
end
class Product < ActiveRecord::Base
belongs_to :depot, inverse_of: :products
belongs_to :company
end
class Zone < ActiveRecord::Base
belongs_to :depot, inverse_of: :zones
end
class User < ActiveRecord::Base
belongs_to :company, inverse_of: :users
end
原始回答
您可能想要修改类的关联方式。
在您的示例中,Depot
类缺少belongs_to :company
。
同样,产品belongs_to :company
在Company
中没有对应物。
后者关联可能会被删除,并转换为has_many through
,因为Depots属于公司,而产品属于Depot。
答案 2 :(得分:0)
您是否遵循Rails方式,以便数据库中的depots
表格具有company_id
字段等等?