diff --git a/app/models/spree/user.rb b/app/models/spree/user.rb index 3ff88d8fa9..7d008ad310 100644 --- a/app/models/spree/user.rb +++ b/app/models/spree/user.rb @@ -41,7 +41,7 @@ module Spree accepts_nested_attributes_for :bill_address accepts_nested_attributes_for :ship_address - after_create :associate_customers + after_create :associate_customers, :associate_orders validate :limit_owned_enterprises @@ -113,6 +113,12 @@ module Spree self.customers = Customer.where(email: email) end + def associate_orders + Spree::Order.where(customer: customers).find_each do |order| + order.associate_user!(self) + end + end + def can_own_more_enterprises? owned_enterprises.reload.size < enterprise_limit end diff --git a/spec/models/spree/user_spec.rb b/spec/models/spree/user_spec.rb index d29cd3d038..881d07b94b 100644 --- a/spec/models/spree/user_spec.rb +++ b/spec/models/spree/user_spec.rb @@ -100,6 +100,7 @@ describe Spree::User do let(:enterprise2) { create(:enterprise) } let!(:customer1) { create(:customer, user: nil, email: email, enterprise: enterprise1) } let!(:customer2) { create(:customer, user: nil, email: email, enterprise: enterprise2) } + let!(:order) { create(:order, customer: customer1) } let!(:user) { create(:user, email: email) } it "should associate these customers with the created user" do @@ -107,6 +108,10 @@ describe Spree::User do expect(user.customer_of(enterprise1)).to be_truthy expect(user.customer_of(enterprise2)).to be_truthy end + + it "should associate the orders passed by customer linked to the created user" do + expect(user.orders.reload).to include order + end end end