How to add some constraints not to allow two way relationship in ROR
I am using ruby on rails to develop some system. In my system i have two models namely course and course_prerequisite. Course A could be prerequisite to course B but course B should never be pre开发者_如何学编程requisite back to course A. how can i enforce this kind of relationship in my system?
One way that I think of is through validations:
class Course < ActiveRecord::Base
has_many :course_prerequisites
belongs_to :user
validate :course_prerequisites
private
def course_prerequisites
unless user.completed_all_prerequisites(course_prerequisites)
errors.add_to_base("Must complete all prerequisites")
end
end
end
Something like that. Note that adding an error programmatically might not invalidate your model. If that happens to you (try it out) either raise an exception or see if the model is valid before saving.
精彩评论