scenario.rb 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  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 ||= YAML.load_file(Rails.root.join('config/icons.yml'))
  23. end
  24. private
  25. def unique_agent_ids
  26. agents.joins(:scenario_memberships)
  27. .group('scenario_memberships.agent_id')
  28. .having('count(scenario_memberships.agent_id) = 1')
  29. .pluck('scenario_memberships.agent_id')
  30. end
  31. def agents_are_owned
  32. unless agents.all? { |s| s.user == user }
  33. errors.add(:agents, 'must be owned by you')
  34. end
  35. end
  36. end