gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 03:51:21 25 4
gpt4 key购买 nike

我在 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 之外,还有其他解决方法吗??

最佳答案

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

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

关于ruby-on-rails - rails 3 中使用的 ActiveRecord 自定义属性在 rails 4 中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27858765/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com