简体   繁体   English

可以属于多个其他对象的对象的模型设计?

[英]model design for object that can belong to multiple other objects?

I wish to build a simple application with 3 types of objects: 我希望用3种类型的对象构建一个简单的应用程序:

  • Article (1st Day in RoR, Why PHP is still awesome, RoR vs. PHP) 文章(RoR的第一天,为什么PHP仍然很棒,RoR与PHP)
  • Author (Bob, Steve, Jen) 作者(Bob,Steve,Jen)
  • Tags (RoR, PHP) 标签(RoR,PHP)

An author writes an article, and and make appropriate tags. 作者撰写文章,并制作适当的标签。

so: 所以:

author has many articles; article belongs to author

But what about tags? 但标签怎么样? I want both articles and authors to have tags. 我希望文章和作者都有标签。

I can imagine that: 我可以想象:

author has many tags; article has many tags

But what about the declaration on the tags model? 但是标签模型上的声明怎么样?

tag belongs to authors; tag belongs to articles

Will the two belongs_to interfere with each other? 这两个人是否会相互干涉?

What i fear is that tag will require both an author and article parent. 我担心的是标签需要作者和文章父母。 and in the event where it has both types of parents, deleting one would delete the tag and the other parent due to foreign key constraints in the database. 并且在它具有两种类型的父项的情况下,由于数据库中的外键约束,删除一个将删除标记和另一个父项。

Thanks in advance! 提前致谢!

You are looking for polymorphyc associations : 您正在寻找多态关联

class Tag < ActiveRecord::Base
  belongs_to :taggable, :polymorphic => true
end

class Author < ActiveRecord::Base
  has_many :tags, :as => :taggable
end

class Article < ActiveRecord::Base
  has_many :tags, :as => :taggable
end

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

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