diff --git a/app/models/vm_or_template.rb b/app/models/vm_or_template.rb index dedb1dcbd7d..b036f2f1a6c 100644 --- a/app/models/vm_or_template.rb +++ b/app/models/vm_or_template.rb @@ -122,7 +122,7 @@ class VmOrTemplate < ApplicationRecord has_many :ems_events_src, :class_name => "EmsEvent" has_many :ems_events_dest, :class_name => "EmsEvent", :foreign_key => :dest_vm_or_template_id - has_many :policy_events, -> { where(["target_id = ? OR target_class = 'VmOrTemplate'", id]).order(:timestamp) }, :class_name => "PolicyEvent" + has_many :policy_events, ->(vm) { where(["target_id = ? AND target_class = 'VmOrTemplate'", vm.id]).order(:timestamp) }, :foreign_key => "target_id" has_many :miq_events, :as => :target, :dependent => :destroy diff --git a/spec/models/vm_or_template_spec.rb b/spec/models/vm_or_template_spec.rb index d9b06e8ff4c..d0da07e8f24 100644 --- a/spec/models/vm_or_template_spec.rb +++ b/spec/models/vm_or_template_spec.rb @@ -1229,4 +1229,12 @@ expect(Vm.new(:location => "test location", :storage => storage).v_datastore_path).to eq("storage name/test location") end end + + context "#policy_events" do + it "returns the policy events with target class of VmOrTemplate and target_id of the vm" do + policy_event = FactoryGirl.create(:policy_event, :target_class => "VmOrTemplate", :target_id => vm.id) + + expect(vm.policy_events).to eq([policy_event]) + end + end end