scenario.rb 1.2KB

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