class ItemBaskets::SaveItemBasketService < ApplicationService attr_reader :user, :params def initialize(user, params) @user = user @params = params 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] - user.item_baskets.pluck(:item_bank_id) items.where(id: item_ids).each do |item| new_item = ItemBasket.new(user_id: user.id, item_bank_id: item.id, item_type: item.item_type) new_item.score = item_score item.item_type new_item.position = item_position item.item_type new_item.save! end end private def item_score item_type if user.item_baskets.where(item_type: item_type).last.present? score = user.item_baskets.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 user.item_baskets.where(item_type: item_type).last&.position.to_i + 1 end end