Model design for an object that may belong to several other objects?

I want to create a simple application with three types of objects:

  • Article (1st day at RoR, why PHP is still cool, RoR vs PHP)
  • Author (Bob, Steve, Jen)
  • Tags (RoR, PHP)

The author writes an article and creates the appropriate tags.

So:

author has many articles; article belongs to author 

But what about tags? I want tags in both articles and authors.

I can imagine that:

 author has many tags; article has many tags 

But what about an ad in a tag model?

 tag belongs to authors; tag belongs to articles 

Will two people interfere with each other?

I am afraid that the tag will require both an author and an article. and in the case when he has both types of parents, deleting one of them will delete the tag and the other parent due to foreign key restrictions in the database.

Thanks in advance!

+4
source share
1 answer

You are looking for polymorphic 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 
+6
source

Source: https://habr.com/ru/post/1396629/


All Articles