是否有在ActiveRecord的'重装'复位实例变量干净的API? [英] Is there a clean API for resetting instance variables on 'reload' in ActiveRecord?

查看:76
本文介绍了是否有在ActiveRecord的'重装'复位实例变量干净的API?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

的ActiveRecord :: Base的模式,我可以重置模型的状态,这是什么,当我得到了它从数据库重装,只要属性我设置映射到表列:

In an ActiveRecord::Base model, I can reset the state of the model to what it was when I got it from the database with reload, as long as the attribute I'm setting maps to a table column:

user = User.first
user.email #=> "email@domain.com"
user.email = "example@site.com"
user.email #=> "example@site.com"
user.reload
user.email #=> "email@domain.com"

但是,如果我添加自定义属性,只有这样,我发现有它的行为同样是这样的:

But if I add a custom attribute, the only way I've found to have it act the same is like this:

class User < ActiveRecord::Base
  attr_accessor :user_agent

  def reload
    super
    self.user_agent = nil
    self
  end
end

我的问题是,有没有一些API,使非数据库列的属性重置重装?是这样的:

My question is, is there some API to make non-database-column-attributes reset on reload? Something like:

class User < ActiveRecord::Base
  # this
  reloadable_attr_accessor :user_agent
  # or this
  def user_agent
    @user_agent
  end

  def user_agent=(value)
    set_instance_var_that_resets_on_reload("@user_agent", value)
  end
end

确实存在于Rails的那个地方?

Does that exist in Rails somewhere?

推荐答案

的ActiveRecord不提供一种方式来做到这一点,对模型的属性就只能充当。

ActiveRecord does not provide a way to do this, it can only acts on the model attributes.

话虽这么说,我觉得更优雅的方式来做到这一点会遍历所有的实例变量,并将其设置为任何你喜欢的:

That being said, I think a more elegant way to do it would be to loop over the ivars and set them to whatever you like :

class User < ActiveRecord::Base
  def reload(options = nil)
    super
    self.instance_variables.each do |ivar|
      next if ivar == '@attributes'
      self.instance_variable_set(ivar, nil)      
    end
  end
 end

请注意,我们跳过@属性,因为AR是照顾它,当你重新加载的属性。

Note that we skip @attributes because AR is taking care of it when you reload the attributes.

这篇关于是否有在ActiveRecord的'重装'复位实例变量干净的API?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆