ruby on rails中Model的关联详解
前言: 一:一对多 例如: select test_associate.mothers.name from test_associate.mothers inner join test_associate.sons on sons.mother_id = mothers.id where sons.name = '小李' ruby代码: class Mother has_many :sons end class Son belongs_to :mother end 解释:一个妈妈又多个孩子,一个儿子属于一个妈妈。 这个 .mother 方法就是由 class Son的belongs_to :mother这句话生成的。 select * from mothers join sons on sons.mother_id = mothers.id where sons.id = 1 详细解释: A:belongs_to :mother 这个就是Rails最典型的根据惯例来编程,声明哪个表对应的是哪个class,再在class之间声明好关联关系。 son = Son.first son.mother # .mother方法, 是由 class Son 中的 belongs_to 产生的。 mother = Mother.first mother.sons # .sons 方法, 是由 class Mother 中的 hash_many 产生的。 二:一对一,比较简单,也不常用,这里不介绍。(老公和老婆) 三:多对多 例如: select teachers.*,students.*,lessons.* from lessons from teachers,join teachers on lessons.teacher_id = teachers.id join students on lessons.student_id = students.id where students.name = '小王' Ruby代码: class Student has_many :lessons has_many :teachers,:through => :lessons end 提示:has_many :teachers,:through => :lessons 相当于 查看小王的老师有哪些,同上面的原始SQL语句。 Student.find_by_name('小王').teachers 以上就是本文给大家分享的全部内容了,给出的示例也非常的简单易懂,希望大家能够喜欢。 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |