数据库关联

model 名字是单数, 例如 app/models/user.rb,

class User < ActiveRecord::Base
end
  • belongs_to 后面必须是单数, 都是小写
  • has_many 后面必须是复数
  • controller 都是复数, 例如 users_controller.
class UsersController < ...
end
belongs_to :mother

等同于下面的:

belongs_to :mother, :class => 'Mother', :foreign_key => 'mother_id'

这个就是Rails最典型的 根据 惯例来编程。 (要知道,在java hibernate中,声明这样关联关系的过程,极其类似:

  1. 声明 哪个表 对应的是 哪个class
  2. 再在class之间, 声明好 关联关系。
  3. 声明关联关系的时候,写上 20行代码。 )

1.belongs_to :mother, rails就能判断出: mothers 表,是一的那一端。 而当前class 是: "class Son", 那么rails 就知道了 两个表的对应关系。

2.:class => 'Mother', 表示, 一的那一端, 对应的model class是Mother. 根据rails的惯例, Mother model对应的是 数据库中的 mothers 表。

3.:foreign_key => 'mother_id', rails就知道了, 外键是 'mother_id'. 而一对多关系中, 外键是保存在 多的那一端(也就是 sons, 所以说,在 sons表中, 必须有一个列, 叫做: mother_id )

所以, 这个复杂的SQL 条件就齐备了, 可以生成了。

上面的ruby代码,配置好之后, 就可以这样调用:

son = Son.first
son.mother  # .mother方法,  是由 class Son 中的 belongs_to 产生的。

mother = Mother.first
mother.sons   # .sons 方法,  是由 class Mother 中的 hash_many  产生的。
class Student
  has_many :lessons
  has_many :teachers, :through => :lessons
  # 上面的简写, 相当于:
  has_many :teachers, :class => 'Teacher', :foreign_key => 'teacher_id', :throught => :lessons
end


class Teachers
  has_many :lessons
  has_many :students, :through => :lessons
end

一个老婆: 有一个老公

class Wife
  belongs_to :husband
end

一个老公: 有一个老婆。

class Husband
  has_one :wife
end
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值