有一个名为Student的模型,它有一个名为:studies_level
的属性。
studies_level
可以具有以下值之一:['school_graduate', 'undergraduate', 'graduate', 'postgraduate', 'doctoral', 'postdoctoral']
还有另一个名为University
如果:studies_level
是研究生,则学生必须使用University_id填写以下属性:undergraduate_university
和:postgraduate_university
有没有办法用Rails模型关系(belongs_to等)来实现这个目标?
答案 0 :(得分:0)
belongs_to :undergraduate_university, class_name: :University
belongs_to :postgraduate_university, class_name: :University
validates :undergraduate_university, presence: true, if: :studies_level=='postgrad'
validates :postgraduate_university, presence: true, if: :studies_level=='postgrad'
validates_associated :undergraduate_university
validates_associated :postgraduate_university