关于ruby on rails:仅将所需的JSON密钥指定为ActiveModel :: Serializers属性

Specify only needed JSON keys as ActiveModel::Serializers attributes

使用ActiveModel :: Serializers解析JSON API时,是否有一种方法不必将JSON中的每个键都指定为属性?

说我只需要:first_name, :last_name, :country作为视图-除非我还指定JSON中的其他键:street_address, :postal_code, :phone, :email,否则我将获得未定义的方法\\'street_address = \\'作为#。

我找到了http://bigastronaut.com/blog/2014/don-t-serialize-just-a-few-give-me-all-attributes,但他的PR尚未被接受:https:// github .com / rails-api / active_model_serializers / pull / 535-同时我还能做些其他事情吗?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
class GetFromJson
  include ActiveModel::Serializers::JSON

  attr_accessor :first_name, :last_name, :country # :street_address, :postal_code, :phone, :email

  def attributes=(hash)
    hash.each do |key, value|
      send("#{key}=", value)
    end
  end

  def self.fetch

    # Code to fetch JSON from API

  end
end

我认为直接在序列化程序中定义所需的内容总是更好,但是我可以看到您的观点,在某些情况下这可能很烦人……您可以做的一件事就是为每个列名定义所有attr_accessors在模型中,如果序列化程序应该对特定的ActiveRecord模型进行序列化。

例如,假设您有一个名为Person的AR模型,只需编写Person.column_names即可找到对象的所有数据库属性,这不会为您提供所需的虚拟属性,但至少\\'默认为您提供所有数据库属性\\'

因此它将类似于:

1
2
3
4
5
class PersonSerializer < ActiveModel::Serializer
  Person.column_names.each {|pcn| attributes pcn}

  #...define other virtual attributes here, etc.
end