-
Notifications
You must be signed in to change notification settings - Fork 43
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
[MNOE-688] Generate relation_id getter and setter for has_one relatio…
…nship
- Loading branch information
Showing
3 changed files
with
33 additions
and
2 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |