如中所示,freeze
禁用更新对象值的功能(在一定程度上)。我如何构建一个方法User.disable_persistence
,它将禁用在该对象和关联对象上创建/保存/更新的能力,无论是直接调用(User.save
)还是间接调用(User.children << child
)。
有没有一个宝石,或一个简单的方法,如:
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
4条答案
按热度按时间0md85ypi1#
问题似乎很简单。不过,棘手的部分是它的
and indirectly (User.children << child)
部分。当父对象(User
)是新记录时,这可以很容易地处理。但如果不是就没那么容易了。这是因为像user#children << child
这样的语句在user
的记录是新的时保存父记录和children
,但在它不是新的时不做同样的事情。在后一种情况下,它只保存child
。这个问题在这个项目上没有自动解决,至少现在没有。开发人员必须首先禁用child
对象上的持久性,以便在后一种情况下实现这一点。参见
author_spec.rb
文件。告诉你整个故事很有帮助。我开发的整个项目是为了回答你的SOW问题:https://github.com/pmatsinopoulos/disable_persistence
任何人想在这方面做出贡献,请随意。
为了方便读者,这里引用了完成整个技巧的代码:
disable_persistence.rb
文件:备注:
A.示例将响应:
#disable_persistence
#enable_persistence
#persistence_disabled?
B.该类将响应:
#disable_persistence
#enable_persistence
#persistence_disabled?
C.有一个
protected
before_save
方法可以检查示例是否可以持久化。它检查示例和类持久性是否都已启用。如果禁用了any,则不允许示例持久化。该功能自动包含在所有
ActiveRecord::Base
类中。这是上面的最后一行。你可能不想那样。如果你不想这样做,你必须在所有你想要这个特性的ActiveRecord::Base
类上调用include DisablePersistence
。在我链接到的rails项目中,我有一个
initializer
,require
是包含此代码的文件。查看config/initializers
否则,你必须自己要求。一些用法的例子(假设一个作者和他们的书):
第一个示例:
第二个例子:
第三个例子:
第四个例子:
第五个例子:
我希望上面的内容能回答你的问题,或者至少对你有帮助。
jrcvhitl2#
你可以添加一个
before_save
过滤器来检查一个boolean字段的值(比如editable
),如果设置为false,这个boolean字段会重定向到根url。代码块将在调用create/save/update
方法之前结束。vcudknz33#
试试
user.readonly!
jgzswidk4#
您可以创建一个事务并抛出一个异常来回滚任何更改。