【Ruby】Ruby的model学习——Active Record Associations

在阅读的过程中有不论什么问题,欢迎一起交流

邮箱:1494713801@qq.com   

QQ:1494713801

 

一、怎样定义关联

    两个model之间经常会存在关联关系,为了解决这些关联引起的复杂操作问题,能够在model定义时定义其关联关系。如:实体customers和orders定义例如以下:

class Customer < ActiveRecord::Base
  has_many:orders, dependent::destroy
end
  
class Order < ActiveRecord::Base
  belongs_to:customer
end
二、关联的类型
  • belongs_to
  • has_one
  • has_many
  • has_many :through
  • has_one :through
  • has_and_belongs_to_many
 1、belongs_to(与has_many相应)

 2、has_one

 3、has_many(与belongs_to相应)

 4、has_many :through
   指many-to-many关联,定义的实体通过第三方实体与还有一个实体有0或多个关联(第三方实体与二者都是belongs_to的关系)。

如:病i人预约医生的样例,每一个预约都相应一个医生和一个病人。可是通过预约医生和病人会有多对多的关系。


 5、has_one :through
   指one-to-one关联,类似于传递依赖,定义的实体通过第三方实体与还有一个实体有一对一的关联。如:每个suppliers都有一个accounts,而每个accounts相应一个account_histories。


 6、The has_and_belongs_to_many Association
   指不须要第三方介入的many-to-many关联。如:组件与部分,每一个组件包含多个部分,而每一个部分又属于多个组件。



三、关联的选项
  • :as
  • :autosave
  • :class_name
  • :dependent
  • :foreign_key
  • :inverse_of
  • :primary_key
  • :source
  • :source_type
  • :through
  • :validate
 1、as:指明为多态关联
 2、autosave:若设为true。当owner实体做出某一操作时会自己主动保存或删除其关联实体的对应操作。
 3、class_name:关联的实体名不能找到相应的实体,通过该属性设置实际的实体。
 4、dependent:当owner实体被摧毁时,关联实体的行为:
          destroy:全部关联实体被摧毁
          delete_all:全部关联实体被直接从数据库删除,不可恢复
          nullify:外键被设为null,不可恢复
          restrict_with_exception:抛出异常提示
          restrict_with_error:抛出错误提示
 5、foreign_key:定义外键的列名
 6、inverse_of:指明反向关联的实体
 7、primary_key:指明关联项的id
 8、through:指明多对多的关系使用的第三方实体
 9、validate:假设设为false,关联关系将会无效。

          



原文地址:https://www.cnblogs.com/mengfanrong/p/5164387.html