Ruby on rails 对称的、自指的HABTM关系
Ruby on rails 对称的、自指的HABTM关系,ruby-on-rails,associations,has-and-belongs-to-many,Ruby On Rails,Associations,Has And Belongs To Many,在我的模式中,我有一个名为Imprintables的模型。在这个模型中,我有一个自我参照关系: 但我无法让它工作,因为我不知道如何知道用户何时尝试删除或插入坐标,而且我甚至不确定这是否是正确答案。铁路诈骗者帮了一点忙,这似乎是一个棘手的案例,因为我有一个模型,它具有对称的自指关系。谢谢你抽出时间 您似乎在这里寻找的是。它们在对象生命周期中的操作之前、之后或期间执行 为了将这些用于您的情况,您可以为CoordinatedImprintable表添加一个模型。然后,无论何时创建、更新或销毁坐标可打
在我的模式中,我有一个名为Imprintables的模型。在这个模型中,我有一个自我参照关系:
但我无法让它工作,因为我不知道如何知道用户何时尝试删除或插入坐标,而且我甚至不确定这是否是正确答案。铁路诈骗者帮了一点忙,这似乎是一个棘手的案例,因为我有一个模型,它具有对称的自指关系。谢谢你抽出时间 您似乎在这里寻找的是。它们在对象生命周期中的操作之前、之后或期间执行 为了将这些用于您的情况,您可以为
CoordinatedImprintable
表添加一个模型。然后,无论何时创建、更新或销毁坐标可打印文件
,都需要对其镜像执行相同的操作
class CoordinateImprintable < ActiveRecord::Base
belongs_to :imprintable
belongs_to :coordinate, class_name: 'Imprintable', foreign_key 'imprintable_id'
after_create :add_mirror
after_update :update_mirror
after_destroy :destroy_mirror
def add_mirror
self.class.find_or_create(imprintable: coordinate, coordinate: imprintable)
end
def update_mirror
if self.changed?
mirror = self.class.find(imprintable: coordinate_was, coordinate: imprintable_was)
mirror.update_attributes(imprintable: coordinate, coordinate: imprintable)
end
end
def destroy_mirror
mirror = self.class.find(imprintable: coordinate, coordinate: imprintable)
mirror.destroy if mirror && !mirror.destroyed
end
end
希望这有帮助!如果有任何问题,请随时发表评论。这要求我不要使用has\u和\u-belish\u-to\u-many关系,对吗?因为HABTM只使用一个没有相关模型的联接表?目前我没有一个可打印的模型。是的,你必须做出改变,但这应该不会太难。我已经在我的答案中添加了这一点。好吧,我花了一些时间和精力,但我终于让它起作用了!谢谢你的帮助没问题!我很高兴为您服务!
INSERT INTO coordinates_imprintables (imprintable_id, coordinate_id) VALUES (1, 2)
INSERT INTO coordinates_imprintables (imprintable_id, coordinate_id) VALUES (2, 1)
class CoordinateImprintable < ActiveRecord::Base
belongs_to :imprintable
belongs_to :coordinate, class_name: 'Imprintable', foreign_key 'imprintable_id'
after_create :add_mirror
after_update :update_mirror
after_destroy :destroy_mirror
def add_mirror
self.class.find_or_create(imprintable: coordinate, coordinate: imprintable)
end
def update_mirror
if self.changed?
mirror = self.class.find(imprintable: coordinate_was, coordinate: imprintable_was)
mirror.update_attributes(imprintable: coordinate, coordinate: imprintable)
end
end
def destroy_mirror
mirror = self.class.find(imprintable: coordinate, coordinate: imprintable)
mirror.destroy if mirror && !mirror.destroyed
end
end
class Imprintable
has_many :coordinate_imprintables
has_many :coordinate, through: :coordinate_imprintables
has_many :mirrored_coordinate_imprintables, class_name: 'CoordinateImprintable', foreign_key: 'coordinate_id'
has_many :mirrored_coordinates, through: :mirrored_coordinate_imprintables, source: :imprintable
end