I want the JSON returned for each model to include a table attribute indicating the database table the object comes from (with STI this isn't the same as the model class) and to look up the appropriate factory function to instantiate objects.
I suppose I could manually override a table attribute for each serializer but that seems really ugly. Is there any way to do this generally?
This works.
Have all my serializers inherit from the following:
class ApplicationSerializer < ActiveModel::Serializer
attributes :table_name
def table_name
object.class.table_name
end
end
A good solution will be extending ActiveRecord::Base
, overriding the attributes
method and then using inheritance.
Extending ActiveRecord::Base
and the override.
class ActiveRecordExtension < ActiveRecord::Base
self.abstract_class = true
def attributes
res = super
res["class_name"] = class_name
res
end
def class_name
self.class.name
end
end
Inheritance
class User < ActiveRecordExtension
end
You can also create a monkey patch but inheritance is neater. The only thing that is useful in a monkey patch is that you will not change inheritance from ActiveRecord::Base
to another class.
I did not use ActiveModel::Serializer
but if you insist on using it you can learn more about it in this cast although I guess each model would need a serializer in contrast to my solution.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.