mission_either_one_relation.rb 1014 Bytes
Newer Older
1
2
3
4
5
6
7
8
9
10
module MissionEitherOneRelation
  extend ActiveSupport::Concern

  included do
    # relates to either Assignment or GroupAssignment (not GroupOffer!)
    belongs_to :assignment, optional: true
    belongs_to :group_assignment, optional: true

    validate :validate_group_assignment_or_assignment_present

Jiri Strojil's avatar
Tmp    
Jiri Strojil committed
11
12
    attr_accessor :mission_id

13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
    def mission=(mission)
      if mission.class.name == 'Assignment'
        self.assignment = mission
      else
        self.group_assignment = mission
      end
    end

    def mission
      group_assignment || assignment
    end

    private

    def validate_group_assignment_or_assignment_present
28
29
30
31
32
33
34
      if assignment.blank? && group_assignment.blank?
        errors.add(:assignment, :insuficient_relation)
        errors.add(:group_assignment, :insuficient_relation)
      elsif assignment.present? && group_assignment.present?
        errors.add(:assignment, :too_many_relations)
        errors.add(:group_assignment, :too_many_relations)
      end
35
36
37
    end
  end
end