Rails 的 Active Record 中 belongs_to 是什么意思?

352 阅读2分钟

Rails 支持六种关联.

关联使用宏式调用实现,用声明的形式为模型添加功能。

例如,声明一个模型属于(belongs_to)另一个模型后,Rails 会维护两个模型之间的“主键-外键”关系,而且还会向模型中添加很多实用的方法。

belongs_to 关联

belongs_to 关联创建两个模型之间一对一的关系,声明所在的模型实例属于另一个模型的实例。用数据库术语来说,就是这个类中包含外键。如果外键在另一个类中,应该使用 has_one 关联。

例如,如果应用中有作者和图书两个模型,而且每本书只能指定给一位作者,就要这么声明图书模型:

class Book < ApplicationRecord
  belongs_to :author
end

belongs_to 关联详解

声明 belongs_to 关联后,所在的类自动获得了五个和关联相关的方法:

  • association
  • association=(associate)
  • build_association(attributes = {})
  • create_association(attributes = {})
  • create_association!(attributes = {})

这五个方法中的 association 要替换成传给 belongs_to 方法的第一个参数(auther)。

Book 模型的每个实例都获得了这些方法:

author
author=
build_author
create_author
create_author!
association 方法

如果关联的对象存在,association 方法会返回关联的对象。如果找不到关联的对象,返回 nil

@author = @book.author
# 关联的对象之前已经取回,会返回缓存版本。如果不想使用缓存版本(强制读取数据库)在父对象上调用 `#reload` 方法。
@author =  @book.reload.author
association=(associate)

association= 方法用于赋值关联的对象。这个方法的底层操作是,从关联对象上读取主键,然后把值赋给该主键对应的对象。

@book.author =  @author
build_association(attributes = {})

build_association 方法返回该关联类型的一个新对象。这个对象使用传入的属性初始化,对象的外键会自动设置,但关联对象不会存入数据库。

@author =  @book.build_author(author_number: 123, author_name: "John Doe")
create_association(attributes = {})

create_association 方法返回该关联类型的一个新对象。这个对象使用传入的属性初始化,对象的外键会自动设置,只要能通过所有数据验证,就会把关联对象存入数据库。

@author =  @book.create_author(author_number: 123, author_name: "John Doe")
create_association!(attributes = {})

与 create_association 方法作用相同,但是如果记录无效,会抛出 ActiveRecord::RecordInvalid 异常。

原文链接