From e4d974aa5864f256e22179db430ea8cdf6508ae8 Mon Sep 17 00:00:00 2001 From: Oleksii Kriuchykhin Date: Fri, 9 Mar 2018 15:34:06 +0100 Subject: [PATCH] Add uniqueness validation for SamplesTable [SCI-2148][SCI-2149] --- app/controllers/user_samples_controller.rb | 17 +++++++++++------ app/models/samples_table.rb | 5 +++-- 2 files changed, 14 insertions(+), 8 deletions(-) diff --git a/app/controllers/user_samples_controller.rb b/app/controllers/user_samples_controller.rb index df8ce9ee8..0aaeeeffc 100644 --- a/app/controllers/user_samples_controller.rb +++ b/app/controllers/user_samples_controller.rb @@ -1,9 +1,9 @@ class UserSamplesController < ApplicationController def save_samples_table_status samples_table = SamplesTable.where(user: @current_user, - team: params[:team]) + team: params[:team]).first if samples_table - samples_table.first.update(status: params[:state]) + samples_table.update(status: params[:state]) else SamplesTable.create(user: @current_user, team: params[:team], @@ -19,14 +19,19 @@ class UserSamplesController < ApplicationController end def load_samples_table_status - @samples_table_state = SamplesTable.find_status(current_user, - current_team).first + samples_table_state = SamplesTable.find_status(current_user, + current_team).first + if samples_table_state.blank? + st = SamplesTable.new(user: current_user, team: current_team) + st.save + samples_table_state = st.status + end respond_to do |format| - if @samples_table_state + if samples_table_state format.json do render json: { - state: @samples_table_state + state: samples_table_state } end end diff --git a/app/models/samples_table.rb b/app/models/samples_table.rb index c33cc1883..84e58edfe 100644 --- a/app/models/samples_table.rb +++ b/app/models/samples_table.rb @@ -1,9 +1,10 @@ class SamplesTable < ApplicationRecord - validates :user, :team, presence: true - belongs_to :user, inverse_of: :samples_tables, optional: true belongs_to :team, inverse_of: :samples_tables, optional: true + validates :user, :team, presence: true + validates :user, uniqueness: { scope: :team } + scope :find_status, ->(user, team) { where(user: user, team: team).pluck(:status) }