Rails 6种关联类型
belongs_to- 声明所在的模型实例属于另一个模型的实例
- 外键在
belongs_to关联所在模型对应的表中,即XXX_id所在的模型 - 在
has_one和belongs_to关联中,必须使用build_*方法构建关联对象。association.build方法是在has_many和has_and_belongs_to_many关联中使用的。创建关联对象要使用create_*方法。 - 声明
belongs_to关联后,所在的类自动获得了五个和关联相关的方法:associationassociation=(associate)build_association(attributes = {})返回对象不存入数据库create_association(attributes = {})返回对象并存入数据库create_association!(attributes = {})不通过valid时抛出异常
belongs_to关联支持下列选项::autosave:class_name:counter_cache:dependent:foreign_key:primary_key:inverse_of:polymorphic:touch:validate:optional
- 在作用域代码块中可以使用任何一个标准的查询方法。下面分别介绍这几个:
whereincludesreadonlyselect
has_one- 这种关联表示模型的实例包含或拥有另一个模型的实例
- 声明
has_one关联后,声明所在的类自动获得了五个关联相关的方法:associationassociation=(associate)build_association(attributes = {})create_association(attributes = {})create_association!(attributes = {})
has_one关联支持下列选项::as:autosave:class_name:dependent:foreign_key:inverse_of:primary_key:source:source_type:through:validate
- 在作用域代码块中可以使用任何一个标准的查询方法。下面介绍其中几个:
whereincludesreadonlyselect
has_manyhas_many关联建立两个模型之间的一对多关系。在belongs_to关联的另一端经常会使用这个关联- 声明
has_many关联后,声明所在的类自动获得了 16 个关联相关的方法:collectioncollection<<(object, …​)collection.delete(object, …​)collection.destroy(object, …​)collection=(objects)collection_singular_idscollection_singular_ids=(ids)collection.clearcollection.empty?collection.sizecollection.find(…​)collection.where(…​)collection.exists?(…​)collection.build(attributes = {}, …​)collection.create(attributes = {})collection.create!(attributes = {})
has_many关联支持以下选项::as:autosave:class_name:counter_cache:dependent:foreign_key:inverse_of:primary_key:source:source_type:through:validate
has_many :through- 建立两个模型之间的多对多关联。这种关联表示一个模型的实例可以借由第三个模型(关系表),拥有零个和多个另一模型的实例。
- 有一个关系表和相对应的model
- 如果想把关联模型当做独立实体使用,要用
has_many :through关联
has_one :through- 通过第三个模型,建立其他两个模型的一对一关系
has_and_belongs_to_many- 不借由第三个模型建立的多对多
- 仍然有第三个关系表但这个表没有model
- 如果不需要使用关联模型,建立
has_and_belongs_to_many关联更简单(不过要记得在数据库中创建联结表)
自联结如何创建
|
|
创建联结表
使用create_join_table创建联结表
|
|
双向关联的问题
Active Record 能自动识别多数具有标准名称的双向关联。然而,具有下述选项的关联无法识别:
:conditions:through:polymorphic:class_name:foreign_key
Active Record 提供了 :inverse_of 选项,可以通过它明确声明双向关联
|
|
inverse_of 有些限制:
- 不支持
:through关联; - 不支持
:polymorphic关联; - 不支持
:as选项;