0

我在 rails 应用程序中有一个表单,允许更新singular_collection_ids属性(关系类型是has_many through)。而且我还需要在更新之前对其进行验证。

验证的问题需要对象的先前值,但是没有方法singular_collection_ids_was来提供此值。此外, singular_collection_ids方法直接与没有临时值的连接表一起使用,所以

self.class.find(id).singular_collection_ids

内部验证没有帮助。

有没有办法在验证阶段获得以前的价值?

4

1 回答 1

0

不确定它是否有效(而且它肯定很古怪),但你可以试试这个:

 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

根据文档,如果回调引发任何错误,则不会删除记录。但是,对此感觉有些不对劲……我会尝试考虑更好的解决方案。

于 2013-06-05T13:48:14.757 回答