rails 3 中使用的 ActiveRecord 自定义属性在 rails 4 中不起作用

ActiveRecord custom attributes used in rails 3 not working in rails 4

我在 rails 3.2 中有以下代码:

class Cart < ActiveRecord::Base
  def self.get_details()
    cart_obj = Cart.first
    cart_obj["custom"] = 1 #Here *custom* is not the column in database
  end
end

我可以在需要时从 cart_obj 对象访问 custom 列。

但我们正计划升级到 rails 4,但它在那里不起作用。除了使用 attr_accessor 之外,还有其他解决方法吗??

在rails4中,使用attr_accessor:

如果您有不需要保留的额外实例数据(即它不是数据库列),您可以使用 attr_accessor 来节省几行代码。

class cart < ActiveRecord::Base
  attr_accessor  :custom

  def self.get_details
    cart_obj = Cart.first
    cart_obj.custom = whatever 
  end
end

听起来像猴子补丁是你要走的路:

class ActiveRecord::Base
  def [](key)
    return super(key) if self.class.column_names.include?(key.to_sym)
    self.class.send :attr_accessor, key.to_sym unless self.class.instance_variable_defined?("@#{key}".to_sym)
    self.instance_variable_get("@#{key}".to_sym)
  end

  def []=(key, val)
    return super(key, val) if self.class.column_names.include?(key.to_sym)
    self.class.send :attr_accessor, key.to_sym unless self.class.instance_variable_defined?("@#{key}".to_sym)
    self.instance_variable_set("@#{key}".to_sym, val)
  end
end

或者如果您想关注它:

module MemoryStorage
  extend ActiveSupport::Concern
  def [](key)
    return super(key) if self.class.column_names.include?(key.to_sym)
    self.class.send :attr_accessor, key.to_sym unless self.class.instance_variable_defined?("@#{key}".to_sym)
    self.instance_variable_get("@#{key}".to_sym)
  end

  def []=(key, val)
    return super(key, val) if self.class.column_names.include?(key.to_sym)
    self.class.send :attr_accessor, key.to_sym unless self.class.instance_variable_defined?("@#{key}".to_sym)
    self.instance_variable_set("@#{key}".to_sym, val)
  end
end

class Cart < ActiveRecord::Base
  include MemoryStorage

  def self.get_details()
    cart_obj = Cart.first
    cart_obj.db_column = 'direct DB access'
    cart_obj["custom"] = 'access to "in-memory" column'
  end
end