How do I avoid a race condition in my Rails app?

前端 未结 2 645
感动是毒
感动是毒 2020-12-02 17:37

I have a really simple Rails application that allows users to register their attendance on a set of courses. The ActiveRecord models are as follows:

class Co         


        
2条回答
  •  心在旅途
    2020-12-02 18:16

    Don't you just have to test if @run.full??

    def create
       unless @user.valid? || @run.full?
          render :action => 'new'
       end
    
       # ...
    end
    

    Edit

    What if you add a validation like:

    class Attendance < ActiveRecord::Base
       validate :validates_scheduled_run
    
       def scheduled_run
          errors.add_to_base("Error message") if self.scheduled_run.full?
       end
    end
    

    It won't save the @attendance if the associated scheduled_run is full.

    I haven't tested this code... but I believe it's ok.

提交回复
热议问题