简体   繁体   English

Ruby on Rails多态关联-案例

[英]Ruby on Rails polymorphic association - case

How would you represent the following case in terms of Ruby-on-Rails associations? 您如何用Ruby-on-Rails关联表示以下情况?

Content (name, description, link) 内容(名称,描述,链接)

has one/belongs to one or more 有一个/属于一个或多个

Author 作者

which is one of these three types: 这是以下三种类型之一:

Person (first_name, surname) OR Artist (artist_name) OR Duo (name1, name2) 人(名字,姓)或艺术家(艺术家名)或二重奏(名字1,名字2)

When I was learning about polymorphic-associations there where 2 sources that really help me 当我学习多态关联时,有2个真正对我有帮助的资源

  1. guides.rubyonrails.org polymorphic-associations guides.rubyonrails.org多态关联
  2. railscasts 1polymorphic-association railscasts 1多态关联

you have to remember that you have a model that will connect with others so you need to have a key value to know to what model and row to connect 您必须记住,您有一个可以与其他模型连接的模型,因此您需要一个关键值来知道要连接的模型和行

class Content < ActiveRecord::Base
  belongs_to :commentable, polymorphic: true
end

class Person < ActiveRecord::Base
  has_many :contents, as: :commentable
end

class Artist < ActiveRecord::Base
  has_many :contents, as: :commentable
end

note that in your Content model you should add commentable_id (as a integer key of the field you are connection to) 请注意,在您的内容模型中,您应该添加commentable_id(作为您要连接的字段的整数键)

commentable_type (as a string, this is going to be the model name that you are connecting to) commentable_type(作为字符串,这将是您要连接的模型名称)

Content (name, description, link, commentable_id, commentable_type)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM