Ruby on rails Rails:如何暂时禁用对象的持久性?
与中一样,Ruby on rails Rails:如何暂时禁用对象的持久性?,ruby-on-rails,ruby,Ruby On Rails,Ruby,与中一样,freeze禁用更新对象值的功能(在一定程度上)。如何构建一个方法User.disable_persistence,该方法将禁用对该对象和关联对象的创建/保存/更新功能,这两个对象都是直接调用(User.save)和间接调用(User.children),您可以在_save过滤器之前添加一个,以检查布尔字段的值(比如说editable),如果设置为false,它将重定向到根url。在调用create/save/update方法之前,该块将结束。您可以创建事务并抛出异常以回滚任何更改。问
freeze
禁用更新对象值的功能(在一定程度上)。如何构建一个方法User.disable_persistence
,该方法将禁用对该对象和关联对象的创建/保存/更新功能,这两个对象都是直接调用(User.save
)和间接调用(User.children),您可以在_save
过滤器之前添加一个,以检查布尔字段的值(比如说editable
),如果设置为false,它将重定向到根url。在调用create/save/update
方法之前,该块将结束。您可以创建事务并抛出异常以回滚任何更改。问题似乎很简单。但棘手的部分是和(User.children非常感谢你!我很敬畏!)
class User < ...
def disable_persistence
# magic here (nullify save, and other methods, prevent callbacks etc.)
class_eval :before_save do
errors.add(:base, "Persistence has been disabled for this object")
end
end
end
module DisablePersistence
extend ActiveSupport::Concern
def disable_persistence
@persistence_disabled = true
end
def enable_persistence
@persistence_disabled = false
end
module ClassMethods
def disable_persistence
@@class_persistence_disabled = true
end
def enable_persistence
@@class_persistence_disabled = false
end
def persistence_disabled?
@@class_persistence_disabled ||= false
end
def persistence_disabled
persistence_disabled?
end
end
included do
attr_reader :persistence_disabled
alias :persistence_disabled? :persistence_disabled
before_save :can_persist?
after_initialize do |base|
base.instance_variable_set(:@persistence_disabled, false)
end
def can_persist?
!persistence_disabled? && !self.class.persistence_disabled?
end
protected :can_persist?
end
end
ActiveRecord::Base.send :include, DisablePersistence
author = Author.new
author.disable_persistence
author.save # will return false and nothing will be saved
author.enable_persistence
author.save # will return true and author will be saved
author = Author.new
author.disable_persistence
book = Book.new
author.books << book
author.save # false and nothing will be saved
author = Author.new
author.save
book = Book.new
book.disable_persistence
author.books << book # nothing will be saved
author = Author.new
author.save
book = Book.new
author.disable_persistence
author.books << book # will be saved indeed, because the book has enabled persistency
author = Author.new
Author.disable_persistence
author.save # will return false and will not save