Saturday, June 7, 2008

Hey yo! one class per kitty


Kitty students start to register courses. A student can have many courses and a course can contain many students. Students and courses are many to many relationship via registration.







class Kitty < ActiveRecord::BASE
has_many :registration
has_many :courses, :through => :registration
end

class Registration < ActiveRecord::BASE
belongs_to :kitty
belongs_to :course
end

class Course < ActiveRecord::BASE
has_many :registration
has_many :kitty, :though => :registration
end


Now, the problem is, how to make sure each kitty is not registered more once for a particular course.

To do this, use validates_uniqueness_of

Validate the uniqueness of a kitty student id (kitty_id) against a course_id:


class Registration < ActiveRecord::BASE
belongs_to :kitty
belongs_to :course

validates_uniqueness_of :kitty_id,
:scope => :course_id,
:message => "one kitty per course!"
end


Remember! when validating the uniqueness via has_many :through, use specific attribute name instead of model name.


validates_uniqueness_of :kitty_id,
:scope => :course_id,
:message => "one kitty per course!"


not


validates_uniqueness_of :kittt,
:scope => :course,
:message => "one kitty per course!"

No comments: