To expose a model via Graphiti, create a class that inherits from ApplicationResource. Within this class, you define attributes, relationships, filters, and sorts.
Key features include:
attribute: Defines a field, its type, and whether it is writable or has specific capabilities like filterable or sortable.has_many, has_one, many_to_many, and polymorphic_has_many: Define relationships between resources.params: A block used within a relationship to inject specific parameters (e.g., applying a filter to a related resource).filter: Custom logic to handle complex queries.sort: Custom logic to handle complex ordering.
class EmployeeResource < ApplicationResource
attribute :first_name, :string
attribute :last_name, :string
attribute :age, :integer
attribute :created_at, :datetime, writable: false
attribute :updated_at, :datetime, writable: false
attribute :title, :string, only: [:filterable, :sortable]
has_many :positions
has_many :tasks
many_to_many :teams
polymorphic_has_many :notes, as: :notable
has_one :current_position, resource: PositionResource do
params do |hash|
hash[:filter][:current] = true
end
end
filter :title, only: [:eq] do
eq do |scope, value|
scope.joins(:current_position).merge(Position.where(title: value))
end
end
sort :title do |scope, value|
scope.joins(:current_position).merge(Position.order(title: value))
end
end