![](/img/trans.png)
[英]Creating relationships in rails 4 (one model can belong to multiple other models)
[英]model design for object that can belong to multiple other objects?
我希望用3種類型的對象構建一個簡單的應用程序:
作者撰寫文章,並制作適當的標簽。
所以:
author has many articles; article belongs to author
但標簽怎么樣? 我希望文章和作者都有標簽。
我可以想象:
author has many tags; article has many tags
但是標簽模型上的聲明怎么樣?
tag belongs to authors; tag belongs to articles
這兩個人是否會相互干涉?
我擔心的是標簽需要作者和文章父母。 並且在它具有兩種類型的父項的情況下,由於數據庫中的外鍵約束,刪除一個將刪除標記和另一個父項。
提前致謝!
您正在尋找多態關聯 :
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.