Ruby on rails API Rails:如何渲染模型&x27;控制器中的自定义属性?

Ruby on rails API Rails:如何渲染模型&x27;控制器中的自定义属性?,ruby-on-rails,Ruby On Rails,在控制器中的#索引操作中,我渲染模型如下。虽然,我想包括一个自定义属性,但它从未被渲染过,我如何才能做到这一点 class MyModel < ApplicationRecord def custom_attr attr1 + attr2 end end class MyModel

在控制器中的#索引操作中,我渲染模型如下。虽然,我想包括一个自定义属性,但它从未被渲染过,我如何才能做到这一点

class MyModel < ApplicationRecord
  def custom_attr
    attr1 + attr2
  end
end
class MyModel
class MyModelsController
这不是一个属性。这只是一个实例方法<代码>属性
实际上是Rails特有的模型特性,它是与元数据结合的setter/getter

class Person
  include ActiveModel::Model
  include ActiveModel::Attributes
  attribute :name
  attribute :age
end

irb(main):009:0> Person.new.attributes
=> {"name"=>nil, "age"=>nil, "birthplace"=>nil}
当您将一个模型呈现为JSON时,rails使用哪个函数调用模型上的
#serializable_hash
。这将基于attributes方法序列化属性。这就是实际传递选项的地方

正如
#custom_attr
实际上不是一个属性,当然它不包括在序列化中

您可以通过以下方式解决此问题:

  • 在模型上重写
    #as_json
    ,以自定义其序列化
  • 使用序列化器层,如ActiveModel::Serializers或JBuilder,自定义模型的JSON表示。(推荐)

我明白了,我的模型中不能有一个未存储在DB中的计算属性吗?我知道了,谢谢。:-)但是,在我的示例中,如何使其只读并进行计算?最简单的方法是使用
MyModel。选择(“*”、“CONCAT('attr'、'''attr2')作为自定义属性(
)。Rails将自动将结果集中的任何列转换为属性。正确的方法是使用序列化层,我只想有一个只读的属性,就像我给出的例子一样。我不明白为什么我在努力寻找我认为最基本的东西。^^我不想编写自定义SQL,我需要用Ruby计算它们;ActiveModel::Serializer不再维护了,它们在这里列出了一些备选方案,如
blueprinter
,添加的序列化层使类似的事情更容易完成。
class Person
  include ActiveModel::Model
  include ActiveModel::Attributes
  attribute :name
  attribute :age
end

irb(main):009:0> Person.new.attributes
=> {"name"=>nil, "age"=>nil, "birthplace"=>nil}