diff --git a/core/app/models/mno_enterprise/base_resource.rb b/core/app/models/mno_enterprise/base_resource.rb index 7b1a22770..486cc00bf 100644 --- a/core/app/models/mno_enterprise/base_resource.rb +++ b/core/app/models/mno_enterprise/base_resource.rb @@ -3,6 +3,7 @@ module MnoEnterprise class BaseResource < ::JsonApiClient::Resource include ActiveModel::Callbacks + include JsonApiClientExtension::HasOneExtension self.site = URI.join(MnoEnterprise.api_host, MnoEnterprise.mno_api_v2_root_path).to_s self.parser = JsonApiClientExtension::CustomParser diff --git a/core/app/models/mno_enterprise/orga_relation.rb b/core/app/models/mno_enterprise/orga_relation.rb index 4ee508e1e..de5deefa1 100644 --- a/core/app/models/mno_enterprise/orga_relation.rb +++ b/core/app/models/mno_enterprise/orga_relation.rb @@ -4,8 +4,11 @@ class OrgaRelation < BaseResource property :created_at, type: :time property :updated_at, type: :time # json_api_client map all primary id as string - property :organization_id, type: :string - property :user_id, type: :string + property :role, type: :string + + has_one :organization + has_one :user + end end diff --git a/core/lib/json_api_client_extension/has_one_extension.rb b/core/lib/json_api_client_extension/has_one_extension.rb new file mode 100644 index 000000000..b2e1b5e81 --- /dev/null +++ b/core/lib/json_api_client_extension/has_one_extension.rb @@ -0,0 +1,27 @@ +module JsonApiClientExtension::HasOneExtension + extend ActiveSupport::Concern + + class_methods do + def has_one(attr_name, options = {}) + class_eval <<-CODE + def #{attr_name}_id=(id) + association = id ? {data: {type: "#{attr_name.to_s.pluralize}", id: id.to_s}} : nil + self.relationships.#{attr_name} = association + end + def #{attr_name}_id + # First we try in the relationship + relationship_definitions = self.relationships.try(:#{attr_name}) + return nil unless relationship_definitions + id = relationship_definitions.dig(:data, :id) + return id if id + # then we for a defined relationship url + if url = relationship_definitions.dig(:links, :related) + association = association_for("#{attr_name}") + return association.data(url).id + end + end + CODE + super + end + end +end