Skip to content

Commit

Permalink
[MNOE-688] Generate relation_id getter and setter for has_one relatio…
Browse files Browse the repository at this point in the history
…nship
  • Loading branch information
x4d3 committed Nov 1, 2017
1 parent f573eb8 commit fef78ca
Show file tree
Hide file tree
Showing 3 changed files with 33 additions and 2 deletions.
1 change: 1 addition & 0 deletions core/app/models/mno_enterprise/base_resource.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
7 changes: 5 additions & 2 deletions core/app/models/mno_enterprise/orga_relation.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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
27 changes: 27 additions & 0 deletions core/lib/json_api_client_extension/has_one_extension.rb
Original file line number Diff line number Diff line change
@@ -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

0 comments on commit fef78ca

Please sign in to comment.