简体   繁体   English

如何为ActiveRecord模型设置model.changed?

[英]How to set model.changed for an ActiveRecord model?

For any ActiveRecord model, I can access the changed attribute to get an array of fields that were changed. 对于任何ActiveRecord模型,我都可以访问change属性来获取已更改字段的数组。

For instance: 例如:

a = Article.find(1)
a.title = "New Title"
a.changed => returns ["title"]

Is there a way for me to set the "changed" attribute myself? 我可以自己设置“更改”属性吗? Suppose I want to make it empty. 假设我要使其为空。 Reason being, I'm actually reading the article attributes from a cache (Redis, but it doesn't matter which), instead of from the database. 原因是,我实际上是从缓存(Redis,但这无关紧要)而不是从数据库中读取文章属性。

Unfortunately, I can't do 不幸的是,我做不到

def getArticleFromCache
    json = getJsonFromCache()
    a = Article.new
    a.attributes = json
    a.changed = [] #doesn't work, changed contains ALL the attributes in the json
    return a
end

What can I do? 我能做什么?

In other words, I want someone who's calling getArticleFromCache to appear as if it's getting it from the database. 换句话说,我希望调用getArticleFromCache的人看起来像是从数据库中获取它一样。

I seems that you basically want to clean the changed history. 看来您基本上是想清除更改的历史记录。

For Rails 3, so you could use a.instance_variable_set(:@changed_attributes, {}) 对于Rails 3,您可以使用a.instance_variable_set(:@changed_attributes, {})

For Rails 4, you can just use a.clear_changes_information 对于Rails 4,您可以只使用a.clear_changes_information

You can do it via private methods from ActiveModel::Dirty 您可以通过ActiveModel::Dirty私有方法来完成此操作

For rails 4 it is: 对于导轨4,它是:

a.send(:clear_changes_information)

For rails 3 it is: 对于导轨3,它是:

a.send(:reset_changes)

Obviously the methods being private gives a pretty big hint that they aren't designed to be called directly but it will work. 显然,私有方法提供了一个很大的暗示,即它们并非旨在直接调用而已,但可以使用。

You may have more success, or a neater solution, by wrapping your Article in another class to decorate it. 通过将Article包裹在另一个类中来装饰它,可能会获得更大的成功或更整洁的解决方案。 You could then override changes in that decorator class to indicate that there are no changes. 然后,您可以覆盖该装饰器类中的changes以指示没有更改。 You'll have to decide how much an article from the cache actually needs to behave like a model class. 您必须决定从缓存中实际上需要多少物品才能像模型类一样工作。 Do you want to save it, for example; 例如,是否要保存它? you might end up with more problems than just trying to hide the changes. 您可能会遇到比仅隐藏更改更多的问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM