Model 关联基础原则
前言: 在掌握 Model 关联机制前,需明确以下关键原则: 1. 关联配置需在两端同时完成,否则可能引发难以排查的错误,且有助于深入理解代码逻辑。 2. Model 类名应使用单数形式,而 Controller 类名通常使用复数形式。 3. `belongs_to` 后接的单数名词必须小写;`has_many` 后接的复数名词也需遵循此规范。
一对多关联配置与原理
一:一对多关联
以王妈妈与两个孩子(小明、小亮)为例:王妈妈拥有多个孩子,而每个孩子仅属于一位母亲。在数据库设计时,通常在“多”的一方添加外键。例如: mothers 表包含 id 和 name 字段。 sons 表包含 id、name 以及 mother_id 字段(mother_id 对应 mothers 表的 id)。 普通SQL查询示例:
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
解释:一个妈妈对应多个孩子,一个孩子属于一个妈妈。 可在 Rails Console 中进行测试: xiao_wang = Son.first mom = xiaowang.mother
`.mother` 方法由 `class Son` 中的 `belongs_to :mother` 声明自动生成。 该操作等效于执行以下 SQL 语句:
select * from mothers
join sons
on sons.mother_id = mothers.id
where sons.id = 1
详细原理解析:
A: belongs_to :mother B: belongs_to :mother, :class => 'Mother', :foreign_key => 'mother_id' A 与 B 等价。
这体现了 Rails “约定优于配置”的典型特性:声明表对应的 Class,并在 Class 间定义关联。 1. `belongs_to :mother` 让 Rails 识别出 mothers 表为“一”的一端,当前 Class 为 `Son`,从而确立两表关系。 2. `:class => 'Mother'` 指定“一”端对应的 Model Class 为 Mother。根据 Rails 惯例,Mother Model 对应数据库中的 mothers 表。 3. `:foreign_key => 'mother_id'` 指明外键为 'mother_id'。在一对多关系中,外键存储在“多”的一端(即 sons 表),因此 sons 表必须包含 mother_id 列。 配置完成后,调用方式如下:
son = Son.first
son.mother # .mother方法, 是由 class Son 中的 belongs_to 产生的。
mother = Mother.first
mother.sons # .sons 方法, 是由 class Mother 中的 hash_many 产生的。
多对多关联与中间表
二:一对一关联较为简单且不常用,此处略过。(如夫妻关系的类比)。
三:多对多关联
例如:一个学生可有多位老师(修读多门课程),一位老师也可教多名学生。由于直接放在任一表中均不合适,需引入中间表(桥梁表): students 表含 id 和 name。 teachers 表含 id 和 name。 lessons 表含 id、name、student_id 和 teacher_id。 原始 SQL 查询如下:
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` 相当于 `has_many :teachers, :class => 'Teacher', :foreign_key => 'teacher_id', :throught => :lessons` class Teachers has_many :lessons has_many :students, :through => :lessons end
查询小王的老师列表,其底层逻辑同上述原始 SQL 语句。
Student.find_by_name('小王').teachers
以上即为本文分享的全部内容,示例简洁易懂,希望能对您有所帮助。