通过主键/外键创建常规关联。
User "Bob", id: 1
Book "The Sponge", id: 1, user_id: 1
外键user_id
是指用户的主键。
多态关联与主键/外键以及对象的“类型”一起使用:
User "Bob", id: 1
Book "The Sponge", id: 1, owner_id: 1, owner_type: "User"
在这里,我们需要两个字段来检索书的所有者:
我们知道所有者的 id 是 1,所有者的类型(类)是“用户”,所以让我们找到 id = 1 的用户!
这意味着您可以拥有多种类型的所有者:poly(几种)-morphic(类型,类)
例如,您可以拥有由 Client 对象拥有的 Book:
Client "XXX", id: 12
Book "Catalog", id: 2, owner_id: 12, owner_type: "Client" # => owner is client #12
Book "Anoying", id: 3, owner_id: 20, owner_type: "User" # => owner is user #20
如何在 Rails 框架中实现多态关联:
class Book < ActiveRecord::Base
belongs_to :owner, polymorphic: true
end
class User < ActiveRecord::Base
has_many :books, as: :owner
end
class Client < ActiveRecord::Base
has_many :books, as: :owner
end
然后你可以通过以下几行找到一本书的所有者:
book = Book.first
book.owner # => return the owner of the book, can be either Client or User