Reputation: 14287
When parsing a JSON API using ActiveModel::Serializers, is there a way not having to specify every single key in the JSON as attributes?
Say I only need :first_name, :last_name, :country
for my views -- unless I also specify the other keys in the JSON, :street_address, :postal_code, :phone, :email
, I will get undefined method 'street_address=' for #.
I found http://bigastronaut.com/blog/2014/don-t-serialize-just-a-few-give-me-all-attributes but his PR has not yet been accepted: https://github.com/rails-api/active_model_serializers/pull/535 -- is there something else I could do meanwhile?
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
Upvotes: 0
Views: 876
Reputation: 2946
I think its always better to directly define what you want in your serializer, but I can see your point that in certain circumstances this could be annoying... one thing you could do, is define all the attr_accessors for every column name in the model, if the serializer is supposed to serialize a specific ActiveRecord model that is.
Say for example you have an AR model named Person
, you can find all the database attributes of the object by just writing Person.column_names
, this won't give you the virtual attributes you may want, but at least 'gives you all database attributes by default'
So it would be something like:
class PersonSerializer < ActiveModel::Serializer
Person.column_names.each {|pcn| attributes pcn}
#...define other virtual attributes here, etc.
end
Upvotes: 1