Reputation: 41
I have 3 models Persona, Assertion and class P2c is inherited from class Assertion
class Persona < ActiveRecord::Base
# create_table "personas", :force => true do |t|
# t.text "name", :null => false
# t.text "description"
# t.datetime "last_change", :null => false
# end
has_many :p2cs
end
class Assertion < ActiveRecord::Base
# create table "assertions", :primary_key => "id", :force => true do |t|
# t.text "rationale",
# end
end
class P2c < Assertion
#create_table "p2cs", :primary_key => "assertion_ptr_id", :force => true do |t|
# t.integer "persona_id", :null => false
# end
belongs_to :persona, :class_name => "Persona", :foreign_key => "persona_id"
end
I need help to write the serialization classes using gem active_model_serializers
Upvotes: 0
Views: 2230
Reputation: 91
I don't understand your question. But I guess you had issue with your STI. STI and polymorphism are not explained in the RailsCast 409, but they talk about it in the documentation.
The key is that you have to specify the serializer. Lets say I have a
class Parent < ActiveRecord::Base
class Child < Parent
I would have the following show/index actions:
def index
render json: children, each_serializer: ParentSerializer
end
def show
render json: child, serializer: ParentSerializer
end
Upvotes: 1
Reputation: 12554
Your question is not clear, but i assume you want to include p2cs in your personnae. as_json
is the preferred way to implement default JSON serialization in rails
class Personna < ActiveRecord::Base
def as_json( options={} )
super( {include: [:p2cs]}.merge options )
end
end
If your problem is to implement different behavior for P2c
and Assertion
, just implement as_json
as needed in each of the classes.
note you may find that blog post about json serialization interesting, because it clarifies the difference between as_json
and to_json
: http://jonathanjulian.com/2010/04/rails-to_json-or-as_json/
the idea is that we need to split json serialization into two steps : build a ruby hash of attributes (as_json), and then serialize it (to_json). This way inheritance and overloading are easier, because we can just process a ruby hash.
Upvotes: 0