From 3ae006d89ece09061de5217ee63ff302e659847a Mon Sep 17 00:00:00 2001 From: Kostiantyn Kostiuk Date: Sat, 26 Aug 2023 22:39:37 +0300 Subject: [PATCH] Initialize all solutions attribute on class init Signed-off-by: Kostiantyn Kostiuk --- app/controllers/uploads_controller.rb | 4 ++-- app/models/solution.rb | 4 +--- app/models/upload.rb | 3 +-- 3 files changed, 4 insertions(+), 7 deletions(-) diff --git a/app/controllers/uploads_controller.rb b/app/controllers/uploads_controller.rb index bcdb1b80..70408824 100644 --- a/app/controllers/uploads_controller.rb +++ b/app/controllers/uploads_controller.rb @@ -28,12 +28,12 @@ def update def resource_params params.require(:upload).permit(:secret, solutions_attributes: %i[task_id file]) - .merge(ips: ip_addresses, device_id: @device_id, contest:) + .reverse_merge(ips: ip_addresses, device_id: @device_id, contest:) end def initialize_resource solutions_attributes = contest.tasks.order(:id).pluck(:id).map { { task_id: _1 } } - @resource = Upload.new solutions_attributes:, contest: + @resource = Upload.new contest:, solutions_attributes: end def build_resource diff --git a/app/models/solution.rb b/app/models/solution.rb index 0d0b8152..64cb8871 100644 --- a/app/models/solution.rb +++ b/app/models/solution.rb @@ -6,7 +6,7 @@ class Solution < ApplicationRecord belongs_to :task, inverse_of: :solutions has_one_attached :file - before_validation :assign_upload_number, on: :create + after_initialize :assign_upload_number, if: -> { new_record? && user && task } after_commit :send_email, on: :create delegate :display_name, :upload_limit, :accepted_ext, :file_names, to: :task, prefix: true, allow_nil: true @@ -18,8 +18,6 @@ def send_email end def assign_upload_number - return unless user && task - # TODO: fix possible race condition self.upload_number = Solution.where(user:, task:).count + 1 end diff --git a/app/models/upload.rb b/app/models/upload.rb index 9a9adac3..cb02934c 100644 --- a/app/models/upload.rb +++ b/app/models/upload.rb @@ -11,12 +11,11 @@ def user def solutions_attributes= attributes attributes = attributes.values if attributes.is_a? Hash - @solutions = attributes.map { Solution.new _1 } + @solutions = attributes.map { Solution.new **_1, user:, ips:, device_id: } end def save solutions.reject! { _1.file.blank? } - solutions.each { _1.assign_attributes user:, ips:, device_id: } solutions.each &:save if valid? end