Specify only needed JSON keys as ActiveModel::Serializers attributes
使用ActiveModel :: Serializers解析JSON API时,是否有一种方法不必将JSON中的每个键都指定为属性?
说我只需要
我找到了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模型进行序列化。
例如,假设您有一个名为
因此它将类似于:
1 2 3 4 5 | class PersonSerializer < ActiveModel::Serializer Person.column_names.each {|pcn| attributes pcn} #...define other virtual attributes here, etc. end |