多态关联 [英] Polymorphic association

查看:86
本文介绍了多态关联的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果您具有多态的belongs_to关联,则引用将添加所需的两列:

If you have polymorphic belongs_to associations then references will add both of the columns required:

create_table :products do |t|
  t.references :attachment, :polymorphic => {:default => 'Photo'}
end

将添加一个attachment_id列和一个字符串attachment_type列,其默认值为照片".

will add an attachment_id column and a string attachment_type column with a default value of ‘Photo’.

这到底是什么意思?

推荐答案

基本上,从定义上讲,多态关联增加了创建与许多其他Rails ActiveRecord模型关联的能力.

Basically, polymorphic association by definition adds ability to create associations with many other Rails ActiveRecord Models.

Rails的两列都知道关联所引用的Model,您拥有attachment_type列(即String)(默认值为"Photo",表名:db中的photos), 而attachment_id类似于该特定模型/表(即照片)的外键.

Both Columns are there for Rails to know which Model the association is referring to, you have the attachment_type column (ie String) (default value is "Photo",table-name: photos in the db), and the attachment_id is sort of like a foreign key to that particular Model/table (ie Photo).

通常,这为您提供了将一个模型与许多其他模型关联的灵活性.

Usually this provides you flexibility to associate one Model to many others.

这篇关于多态关联的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆