在梳理完文档之后,我很难理解我应该使用什么回调。
伪码:
如果child_id和outage_id不存在
创建关系(INSERT语句)
如果outage_id被更改
修改关系(UPDATE语句)
这些插入和更新是通过collection_check_boxes处理的。
有3种模式。关系,断电,和孩子。
class Outage < ApplicationRecord
has_many :relationships
has_many :children, through: :relationships
end
class Child < ApplicationRecord
end
class Relationship < ApplicationRecord
belongs_to :outage
belongs_to :child
validate :check_if_exists, if: :outage_id_changed?
private
def check_if_exists
Relationship.where(child_id: self.child_id).update_all(outage_id: self.outage_id)
end
end我现在面临的问题是,无论发生什么,UPDATE总是发生在INSERT之前。只有当记录存在并且更改了UPDATE时,才会发生outage_id。
任何关于我在这里做错了什么的洞察力都将不胜感激。
发布于 2017-12-05 18:35:52
你可以试试这个,
class Relationship < ApplicationRecord
before_update :check_if_exists, if: :outage_id_changed?
private
def check_if_exists
# Your logic
end
end注意:您的代码check_if_exists中的也将在create上运行,因为在创建过程中outage_id正在从nil更改为<some_id>
但是,使用before_update将确保它只在更新时运行。
还请注意,您使用的是update_all,它会产生一个直接的db查询,并且不会被包装在事务中。这意味着,如果更新失败,通过update_all所做的更改将不会回滚。
https://stackoverflow.com/questions/47656245
复制相似问题