Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Validate presence of associations in a many-to-many relation

In my Rails app I have a many-to-many relationship between 2 models Teacher and Course through a join table. I'd like to create some sort of validation where a course can't be created without being associated to at least one teacher (it is assumed that all teachers are in the database by the time we are adding a new course). This would be easy to do if this was a one-to-many relationship, but with a many-to-many relationship, we need to save the course before we can associate it with teachers.

My initial plan was to override Rails create method in the Course model to allow passing teacher_ids and validate presence of at least one teacher_id before saving the course, but I'm not sure this is a nice approach.

like image 709
Sbbs Avatar asked Jun 29 '14 19:06

Sbbs


1 Answers

You should write custom validation, which is quite easy (please adapt to your code):

class Course < ActiveRecord::Base

  has_and_belongs_to_many :teachers

  validate :has_one_teacher_at_least

  def has_one_teacher_at_least
    if teachers.empty?
      errors.add(:teachers, "need one teacher at least")
    end
  end
end

That way, you'll only be able to create courses if associated to one teacher like so:

teacher = Teacher.create()
course = Course.new()
course.teachers << teacher
course.save!
like image 54
Arnaud Rinquin Avatar answered Nov 02 '22 11:11

Arnaud Rinquin