scenario.rb 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. class Scenario < ActiveRecord::Base
  2. include HasGuid
  3. belongs_to :user, :counter_cache => :scenario_count, :inverse_of => :scenarios
  4. has_many :scenario_memberships, :dependent => :destroy, :inverse_of => :scenario
  5. has_many :agents, :through => :scenario_memberships, :inverse_of => :scenarios
  6. validates_presence_of :name, :user
  7. validates_format_of :tag_fg_color, :tag_bg_color,
  8. # Regex adapted from: http://stackoverflow.com/a/1636354/3130625
  9. :with => /\A#(?:[0-9a-fA-F]{3}){1,2}\z/, :allow_nil => true,
  10. :message => "must be a valid hex color."
  11. validate :agents_are_owned
  12. def destroy_with_mode(mode)
  13. case mode
  14. when 'all_agents'
  15. Agent.destroy(agents.pluck(:id))
  16. when 'unique_agents'
  17. Agent.destroy(unique_agent_ids)
  18. end
  19. destroy
  20. end
  21. def self.icons
  22. @icons ||= begin
  23. YAML.load_file(Rails.root.join('config/icons.yml'))
  24. end
  25. end
  26. private
  27. def unique_agent_ids
  28. agents.joins(:scenario_memberships)
  29. .group('scenario_memberships.agent_id')
  30. .having('count(scenario_memberships.agent_id) = 1')
  31. .pluck('scenario_memberships.agent_id')
  32. end
  33. def agents_are_owned
  34. unless agents.all? { |s| s.user == user }
  35. errors.add(:agents, 'must be owned by you')
  36. end
  37. end
  38. end