我在rails应用程序中有一个表单,允许更新singular_collection_ids属性(关系类型是,has_many,通过)。我还需要在更新之前验证它。
验证问题需要以前的对象值,但是没有方法singular_collection_ids_was来提供这个值。另外,singular_collection_ids方法直接处理没有临时值的联接表,因此
self.class.find(id).singular_collection_ids
内部验证没有帮助。
在验证阶段是否有获得先前值的方法?
发布于 2013-06-05 05:48:14
不确定它是否有效(而且确实很奇怪),但您可以尝试如下:
class Player
has_many :join_models, before_remove: :prevent_achievement_removal
def prevent_achievement_removal( join_model )
errors.add( :base, "Cannot remove an achievement this way !" )
raise ::ActiveRecord::RecordInvalid
end
end
根据医生,如果回调引发任何错误,则不会删除记录。不过,这件事有些不太对劲.我会考虑一个更好的解决方案。
https://stackoverflow.com/questions/16933654
复制