ruby on rails - How to validate the state of a join model before creation -


as got downvoted first time, time try clear possible goals. if they're not clear, please let me know what's missing.


i have course , students have has_many through: relationship. when create record newcourseparticipation, check if course full (via full? method).

what best way that? first impulse introduce conditional check in create action of controller, i'm doing validation in course model. think best "before_create" validation in courseparticipation model. not sure how though.

my course model

class course < activerecord::base   has_many :students, through: course_participations   has_many :course_participations end 

and student model

class student < activerecord::base   has_many :courses, through: course_participations end 

the join model

class courseparticipation < activerecord::base   belongs_to :student   belongs_to :course end 

in userscontroller:

def create   @course = course.find(params[:course_id])   @student = student.find_or_create_by(user_params)   if @student     @course.participate(@student)   end end 

in course model:

  def full?     self.students.count >= self.max_students   end    def participate(student)     if !self.full?       course_booking = courseparticipation.new(course_id: self.id, student_id: student.id)       course_booking.save     else       self.errors.add(:course_full, "course full")     end   end 

goal:

  • best place validate course not full , create instance of courseparticipation

try this:

class courseparticipation < activerecord::base   belongs_to :student   belongs_to :course    before_create :check_class_size    private   def check_class_size     !self.course.full?   end end 

Comments

Popular posts from this blog

google chrome - Developer tools - How to inspect the elements which are added momentarily (by JQuery)? -

angularjs - Showing an empty as first option in select tag -

php - Cloud9 cloud IDE and CakePHP -