Skip to content

Commit

Permalink
Add ancestors relationship to page serializer
Browse files Browse the repository at this point in the history
Useful if you want to serialize the page categorizations
in a breadcrumb for instance.
  • Loading branch information
tvdeyen committed Apr 27, 2021
1 parent ae4b0c3 commit eee59ec
Show file tree
Hide file tree
Showing 3 changed files with 18 additions and 0 deletions.
4 changes: 4 additions & 0 deletions app/models/alchemy/json_api/page.rb
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,10 @@ def fixed_element_ids
@_fixed_element_ids ||= fixed_elements.map(&:id)
end

def ancestor_ids
@_ancestor_ids ||= ancestors.map(&:id)
end

private

def element_repository
Expand Down
6 changes: 6 additions & 0 deletions app/serializers/alchemy/json_api/page_serializer.rb
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,12 @@ class PageSerializer

belongs_to :language, record_type: :language, serializer: ::Alchemy::JsonApi::LanguageSerializer

has_many :ancestors, record_type: :page, serializer: self do |page|
page.ancestors.map do |ancestor|
Alchemy::JsonApi::Page.new(ancestor, page_version_type: page.page_version_type)
end
end

# All public elements of this page regardless of if they are fixed or nested.
# Used for eager loading and should be used as the +include+ parameter of your query
has_many :all_elements, record_type: :element, serializer: ELEMENT_SERIALIZER
Expand Down
8 changes: 8 additions & 0 deletions spec/serializers/alchemy/json_api/page_serializer_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -66,5 +66,13 @@
expect(subject[:language]).to eq(data: { id: page.language_id.to_s, type: :language })
end
end

it "has ancestors relationship" do
expect(subject[:ancestors]).to eq(
data: [
{ id: page.parent_id.to_s, type: :page },
],
)
end
end
end

0 comments on commit eee59ec

Please sign in to comment.