我有这个模型,LeaveManagementRule
。 Rule
有一个sender
,一个receiver
。发件人可以是Role
或User
(对于收件人也是如此):
class LeaveManagementRule < ActiveRecord::Base
belongs_to :sender, polymorphic: true # Sender can be a Role or a User
belongs_to :receiver , polymorphic: true # receiver can be a Role or a User
...
end
以下是User
型号:
class User < ActiveRecord::Base
has_many :leave_management_rules, as: :sender, dependent: :destroy
has_many :leave_management_rules, as: :receiver, dependent: :destroy
...
end
Role
模型与用户模型相同。出于这个问题的目的,我觉得不需要详细说明。
以下是db:{/ p>中leave_management_rules
表的摘录
mysql> select * from leave_management_rules;
+----+-----------+-------------+--------+-------------+---------------+------------+
| id | sender_id | sender_type | action | receiver_id | receiver_type | project_id |
+----+-----------+-------------+--------+-------------+---------------+------------+
| 1 | 56 | User | 1 | 19 | Role | 33 |
| 2 | 146 | User | 2 | 56 | User | 33 |
+----+-----------+-------------+--------+-------------+---------------+------------+
我们将重点关注user_id: 56
,它出现在此处的两个条目中(作为条目1的sender
,作为条目2的receiver
。
现在,我正在尝试删除Rails控制台中的用户56:
irb(main):020:0> u = User.find(56)
irb(main):021:0> u.destroy
所以,我希望我的leave_management_rules
表现在是空的。但仍有一个条目:
mysql> select * from leave_management_rules;
+----+-----------+-------------+--------+-------------+---------------+------------+
| id | sender_id | sender_type | action | receiver_id | receiver_type | project_id |
+----+-----------+-------------+--------+-------------+---------------+------------+
| 1 | 56 | User | 1 | 19 | Role | 33 |
+----+-----------+-------------+--------+-------------+---------------+------------+
我的代码中有什么问题吗?
我正在运行Rails 4.2.4
答案 0 :(得分:0)
我认为你在double-polimymorphic
协会做得不好。尝试这样的事情:
class UserRulesRelation < ActiveRecord::Base
belongs_to :origin, polymorphic: true
belongs_to :leave_management_rules, polymorphic: true
end
class User < ActiveRecord::Base
has_many :user_rules_relations, as: :origin, dependent: :destroy
has_many :sent, through: :user_rules_relations, source: :leave_management_rules, source_type: "User"
has_many :received, through: :user_rules_relations, source: :leave_management_rules, source_type: "LeaveManagementRule"
end
class LeaveManagementRule < ActiveRecord::Base
has_many :user_rules_relations, as: :origin, dependent: :destroy
has_many :sent, through: :user_rules_relations, source: :leave_management_rules, source_type: "User"
has_many :received, through: :user_rules_relations, source: :leave_management_rules, source_type: "LeaveManagementRule"
end
答案 1 :(得分:0)
我没有找到为什么dependent: :destroy
回调无法正确触发的答案。
相反,我为before_destroy
和User
模型编写了自定义Role
回调:
before_destroy :destroy_leave_management_rules
def destroy_leave_management_rules
as_sender = LeaveManagementRule.where(sender: self)
as_receiver = LeaveManagementRule.where(receiver: self)
as_sender.destroy_all
as_receiver.destroy_all
end