From 2a465aca3ba5bc0be458c792e8e775a4e1e30c84 Mon Sep 17 00:00:00 2001 From: Justin Edmund Date: Sun, 8 Jan 2023 20:13:09 -0800 Subject: [PATCH] Move shortcode setting to before_save on Party model --- app/controllers/api/v1/parties_controller.rb | 13 +------------ app/models/party.rb | 11 +++++++++++ 2 files changed, 12 insertions(+), 12 deletions(-) diff --git a/app/controllers/api/v1/parties_controller.rb b/app/controllers/api/v1/parties_controller.rb index ff4ea0b..f5171d8 100644 --- a/app/controllers/api/v1/parties_controller.rb +++ b/app/controllers/api/v1/parties_controller.rb @@ -8,12 +8,7 @@ module Api before_action :set, only: %w[update destroy] def create - party = Party.new(shortcode: random_string) - party.user = current_user if current_user - - if party_params - party.attributes = party_params - end + party = Party.new(party_params.merge(user: current_user)) # unless party_params.empty? # party.attributes = party_params @@ -125,12 +120,6 @@ module Api end end - def random_string - num_chars = 6 - o = [('a'..'z'), ('A'..'Z'), (0..9)].map(&:to_a).flatten - (0...num_chars).map { o[rand(o.length)] }.join - end - def set_from_slug @party = Party.where('shortcode = ?', params[:id]).first @party.favorited = current_user && @party ? @party.is_favorited(current_user) : false diff --git a/app/models/party.rb b/app/models/party.rb index e9840ff..b8066d0 100644 --- a/app/models/party.rb +++ b/app/models/party.rb @@ -43,6 +43,7 @@ class Party < ApplicationRecord has_many :favorites + before_save :set_shortcode ##### ActiveRecord Validations validate :skills_are_unique @@ -58,6 +59,16 @@ class Party < ApplicationRecord private + def set_shortcode + self.shortcode = random_string + end + + def random_string + num_chars = 6 + o = [('a'..'z'), ('A'..'Z'), (0..9)].map(&:to_a).flatten + (0...num_chars).map { o[rand(o.length)] }.join + end + def skills_are_unique skills = [skill0, skill1, skill2, skill3].compact