用户不能有两个具有相同类别的目标- RubyOnRails

vulvrdjw  于 2022-11-04  发布在  Ruby
关注(0)|答案(1)|浏览(128)

我正在尝试实现我的create方法,以避免创建具有相同类别的两个目标。

def create
   # submission of new objective form
   @category = Category.find(params[:category_id])
   @objective = Objective.new(objective_params)
   @objective.user_id = current_user.id
   @objective.category_id = @category.id
   @objective.start_date = Date.today

   if current_user.objectives.count >= 1 && current_user.objectives.where(category_id: @objective.category_id).exists?
     @used_category = current_user.objectives.where(category_id: @objective.category_id).first.category.id
     if @used_category == @objective.category_id
       flash[:alert] = "Tu as déjà un objectif appartenant à cette catégorie"
     end
   else
     @objective.save!
     if @objective.persisted?
       # creates periods for the objective
       @objective.total_periods.times do |i|
         period =
           {
             period_number:  (Date.today + (i*7).days).strftime("%V"),
             period_score: 0,
             created_at: Date.today,
             objective_id: @objective.id
           }
         p1 = Period.new( period_number: period[:period_number], created_at: period[:created_at], period_score: period[:period_score], objective_id: period[:objective_id])
         p1.save!
       end
     end
   end

   if current_user.objectives.count == 1
     notification = ObjectiveNotification.with(post: Post.where(user_id: User.find_by(username: "Aitio"), title: "Participez à un objectif en commun !")[0])
     notification.deliver(@objective.user)
     notifications = current_user.notifications.unread.count
     Turbo::StreamsChannel.broadcast_replace_to("mynotif", target: "mynotif_#{current_user.id}_value", partial: 'shared/stream_mynotif', locals: { notifications: notifications, userid: current_user.id })
   end

   # replaces form with create.turbo_stream.erb
   respond_to do |format|
     format.turbo_stream
   end
 end

但我似乎不能使它工作。我在想如果没有走得太远,也许有一个更简单的解决办法。
如果有人有想法,让我知道!谢谢

o75abkj4

o75abkj41#

不确定我是否正确理解了您的问题,但在这种情况下,对模型进行自定义验证似乎更有意义,因为它将阻止保存并在视图中标记表单上的错误,而无需在控制器中进行额外的检查。
与此类似的内容:

class Objective < ApplicationRecord

validates :check_category

def check_category
  if self.user.objectives.where(category_id: self.category_id).present?
    errors.add :category_id, "Tu as déjà un objectif appartenant à cette catégorie"
  end
end

相关问题