Commit f348b749 authored by Alexandre Friquet's avatar Alexandre Friquet

Prevent deletion of all subscriptions associated to an adherent: refs #86.

parent 1863e17c
......@@ -21,7 +21,7 @@
# along with OLIGAA. If not, see <http://www.gnu.org/licenses/>.
#
class Adherent < ApplicationRecord
has_many :subscriptions, dependent: :destroy
has_many :subscriptions
belongs_to :medico_social_org, class_name: 'Member', optional: true
validates :last_name, :first_name, :born_on, :permit_number, presence: true
......
......@@ -22,12 +22,13 @@
#
class Subscription < ApplicationRecord
belongs_to :member
belongs_to :adherent, dependent: :destroy
belongs_to :adherent
accepts_nested_attributes_for :adherent
has_many :performance_subscriptions, dependent: :destroy
has_many :performances, through: :performance_subscriptions
after_create :set_platform_number
before_destroy :destroy_adherent_if_necessary
scope :for_performances, ->(performance_ids) { joins(:performances).where(performance_subscriptions: {performance_id: performance_ids}).distinct }
scope :by_adherent_name, -> { joins(:adherent).order('adherents.first_name','adherents.last_name') }
......@@ -70,4 +71,8 @@ class Subscription < ApplicationRecord
def set_platform_number
self.update_attribute(:platform_number, SubscriptionNumber.new(self).label)
end
def destroy_adherent_if_necessary
adherent.destroy if Subscription.where(adherent: self.adherent).count == 1
end
end
......@@ -160,5 +160,24 @@ RSpec.describe Subscription, type: :model do
expect(subscription.billing_status).to eq 'billed'
end
end
context "on deletion" do
it "deletes adherent if not associated to any other subscription" do
subscription = create :subscription
expect {
subscription.destroy
}.to change(Adherent, :count).from(1).to(0)
end
it "does not delete adherent if associated to another subscription" do
adherent = create :adherent
subscription = create :subscription, adherent: adherent
create :subscription, adherent: adherent
expect {
subscription.destroy
}.to_not change(Adherent, :count)
expect(Subscription.count).to eq 1
end
end
end
end
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment