From 60a1cc22676d3c4dd981f8ab876f5d219684a5d0 Mon Sep 17 00:00:00 2001 From: kikito Date: Fri, 14 Aug 2015 20:24:19 +0200 Subject: [PATCH] Adds User.is_organization and User.organization_name --- app/models/user.rb | 18 ++++++++++++++---- spec/models/user_spec.rb | 30 ++++++++++++++++++++++++------ 2 files changed, 38 insertions(+), 10 deletions(-) diff --git a/app/models/user.rb b/app/models/user.rb index 9fb1f65c4..3b14879ca 100644 --- a/app/models/user.rb +++ b/app/models/user.rb @@ -4,9 +4,10 @@ class User < ActiveRecord::Base acts_as_voter - validates :first_name, presence: true, if: :use_first_name? - validates :last_name, presence: true, if: :use_last_name? - validates :nickname, presence: true, if: :use_nickname? + validates :first_name, presence: true, if: :use_first_name? + validates :last_name, presence: true, if: :use_last_name? + validates :nickname, presence: true, if: :use_nickname? + validates :organization_name, presence: true, if: :is_organization has_one :administrator has_one :moderator @@ -16,6 +17,11 @@ class User < ActiveRecord::Base scope :moderators, -> { joins(:moderator) } scope :organizations, -> { joins(:organization) } + attr_accessor :organization_name + attr_accessor :is_organization + + after_save :create_associated_organization + def name return nickname if use_nickname? return organization.name if organization? @@ -44,11 +50,15 @@ class User < ActiveRecord::Base private def use_first_name? - !use_nickname? && !organization? + !is_organization && !use_nickname? end def use_last_name? use_first_name? end + def create_associated_organization + create_organization(name: organization_name) if is_organization + end + end diff --git a/spec/models/user_spec.rb b/spec/models/user_spec.rb index b357d2818..ce9fb5989 100644 --- a/spec/models/user_spec.rb +++ b/spec/models/user_spec.rb @@ -123,16 +123,34 @@ describe User do expect(subject.organization?).to be true end - it "deactivates the validation of first_name and last_name" do - subject.first_name = nil - subject.last_name = nil - expect(subject).to be_valid - end - it "calculates the name using the organization name" do expect(subject.name).to eq(subject.organization.name) end end end + describe "is_organization" do + before(:each) { subject.is_organization = true } + + it "deactivates the validation of first_name and last_name, and activates the validation of organization_name" do + subject.first_name = nil + subject.last_name = nil + subject.organization_name = nil + expect(subject).to_not be_valid + + subject.organization_name = 'org' + expect(subject).to be_valid + end + + it "triggers the creation of an associated organization using organization_name" do + expect(subject.organization).to_not be + + subject.is_organization = true + subject.organization_name = 'org' + subject.save + + expect(subject.organization).to be + end + end + end