Last active
September 8, 2017 00:16
-
-
Save Startouf/937492b1ad86aa035b9660a519802f18 to your computer and use it in GitHub Desktop.
Conditional rendering of relationship for tricky situation
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
```ruby | |
class User | |
embeds_many :attacker_performance | |
embeds_many :defender_performance | |
has_many :matches_as_attacker | |
has_many :matches_as_defender | |
end | |
class AttackerPerformance | |
embedded_in :user | |
belongs_to :match | |
field :mobility | |
field :attacks | |
end | |
class DefenderPerformance | |
embedded_in :user | |
belongs_to :match | |
field :balls_stopped | |
end | |
class Match | |
belongs_to :attacker, class: User, inverse_of: :matches_as_attacker | |
belongs_to :defender, class: User, inverse_of: :matches_as_defender | |
# attacker and defender reports are available through each user only | |
end | |
class MatchResource < ApplicationJsonapiSuiteResource | |
allow_sideload :attack_performances, type: :has_many, resource: AttackPerformanceArrayResource | |
scope do |matches| | |
User.in(:'attacker_performance.match_id' => matches.pluck(:id)).map(&:attack_performances) | |
# Ideal would be instead of the `User.in(...) ` | |
# | |
# context.current_user.attacker_performances | |
# | |
# but context.current_user is not available :'( | |
end | |
assigns do |matches, attack_performances| | |
matches.each do |match| | |
match.set_relation(:attacker_performance, attack_performances.detect { |p| p.match == match } | |
end | |
end | |
end | |
class SerializableMatch < ApplicationJsonapiRbSerializer | |
has_one :attacker_performance | |
end | |
class SerializableAttackerPerformance < ApplicationJsonapiRbSerializer | |
attributes :mobility, :attacks | |
end | |
``` | |
# Here I would need to allow sideloading or rendering the attack performance only if the `context.current_user` is the guy who performed the attack |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment