Skip to content

Commit

Permalink
feat(subscription): run validations when needed
Browse files Browse the repository at this point in the history
* add optional params for user.
* accept nested attrs for both :user and :plan
  • Loading branch information
castrolem committed Aug 19, 2019
1 parent 83e082a commit 9911321
Show file tree
Hide file tree
Showing 2 changed files with 10 additions and 4 deletions.
13 changes: 10 additions & 3 deletions app/models/subscription.rb
Original file line number Diff line number Diff line change
@@ -1,9 +1,16 @@
# frozen_string_literal: true

class Subscription < ApplicationRecord
belongs_to :user
belongs_to :user, optional: true
belongs_to :plan

validates :user_id, :plan_id, presence: true
validates :user_id, uniqueness: { scope: %i[plan_id active] }
accepts_nested_attributes_for :user
accepts_nested_attributes_for :plan

validates :plan_id, presence: true
validates :user_id, uniqueness: { scope: %i[plan_id active] }, if: :user?

def user?
!user_id.blank?
end
end
1 change: 0 additions & 1 deletion spec/models/subscriptions_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,6 @@
end

describe 'validations' do
it { is_expected.to validate_presence_of(:user_id) }
it { is_expected.to validate_presence_of(:plan_id) }
it { is_expected.to validate_uniqueness_of(:user_id).scoped_to(:plan_id, :active).ignoring_case_sensitivity }
end
Expand Down

0 comments on commit 9911321

Please sign in to comment.