class ExaminationItems::SaveItemService < ApplicationService attr_reader :user, :params, :exam def initialize(user, params, exam) @user = user @params = params @exam = exam end def call raise("请选择试题") if params[:item_ids].blank? # 只能选用公共题库或是自己的题库 items = ItemBank.where(public: 1).or(ItemBank.where(user_id: user.id)) # 已选到过试题篮的不重复选用 item_ids = params[:item_ids] - exam.examination_items.pluck(:item_bank_id) items.where(id: item_ids).each do |item| ActiveRecord::Base.transaction do item_score = item_score item.item_type item_position = item_position item.item_type new_item = ExaminationItem.new new_item.new_item(item, exam, item_score, item_position) end end end private def item_score item_type if exam.examination_items.where(item_type: item_type).last.present? score = exam.examination_items.where(item_type: item_type).last.score else score = case item_type when "SINGLE", "MULTIPLE", "JUDGMENT" 5 when "PROGRAM" 10 else 5 end end score end def item_position item_type exam.examination_items.where(item_type: item_type).last&.position.to_i + 1 end end