开发者

How to add some constraints not to allow two way relationship in ROR

开发者 https://www.devze.com 2023-02-02 10:23 出处:网络
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开发者

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.

0

精彩评论

暂无评论...
验证码 换一张
取 消