【发布时间】:2019-02-21 15:02:25
【问题描述】:
我想为我的一些模型添加虚拟列,但要让它们的值由 ActiveRecord 语句(如Product.first)返回,以便我可以使用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列。 - 通过 ActiveRecord 访问
Product应该返回一个Product对象,其中包含一个total键,该键具有基于模型其他属性的计算值。
这可能吗?
我真的不想用大量手动插入这些虚拟列的代码替换每个 to_json 调用......
【问题讨论】:
-
您在项目中使用 ActiveModelSerializers 吗?如果是,您可以使用
total方法创建一个单独的序列化程序并在所需的控制器操作中使用它
标签: ruby-on-rails ruby-on-rails-5 rails-activerecord