我想将虚拟列添加到我的某些模型中,但要让它们的值由Product.first
之类的ActiveRecord语句返回,以便可以使用Product.first.to_json
之类的语句将虚拟列与产品一起输出API请求。
列的值取决于其他模型属性。我不希望这些列保留到数据库中。
我尝试过:
class Product < ApplicationRecord
def total
price + tax
end
end
但是Product.first
不包括总数。
class Product < ApplicationRecord
attribute :total, :decimal, default: -> { 0.0 }
end
向返回的对象添加total: 0.0
,但
class Product < ApplicationRecord
attribute :total, :decimal, default: -> { price + tax }
end
失败,例如消息>>
#<NameError: undefined local variable or method `price' for #<Class:0x0000557b51c2c960>>
和
class Product < ApplicationRecord attribute :total, :decimal, default: -> { 0.0 } def total price + tax end end
仍然返回
total: 0.0
。
我什至不确定attribute
是否是执行此操作的正确方法,因为文档似乎暗示它已绑定到列。
总结:
products
表不应包含total
列。Product
应该返回一个Product
对象,该对象包括一个total
键,该键具有基于模型的其他属性的计算值。这甚至有可能吗?
我真的
不想用大量代码手动插入这些虚拟列来替换每个to_json
调用...我想向我的某些模型中添加虚拟列,但是要让它们的值由ActiveRecord语句(例如Product.first)返回,以便我可以使用Product.first.to_json这样的语句来输出...
as_json
以包括您的方法。 methods
选项