2014-10-06 31 views
1

最近我碰到,我需要一個模型添加到另一個模型不止一次幾個方案。Rails的一個模型添加到另一種模式的兩倍

示例:

說一個用戶有一個帖子。但該帖子也應該能夠與其他用戶共享,以便這些用戶可以查看/編輯該帖子。所以帖子應該屬於一個用戶,但也應該有一個用戶的數組,也可以編輯它。

或者說一個調查應該有很多問題,但也應該有一些問題,是獨立的篩選問題。所以調查應該有很多問題,但也可能有很多篩選問題。

我怎麼會去有關添加指向第二個數據庫字段相同的模型作爲不同領域?現在郵政將有user_id:integer,每個問題將有一個survey_id:integer

對於有問題的調查,我想我大概一個「篩選」布爾屬性只是添加了問題,然後就被篩選屬性添加的所有問題的survey.questions陣列和過濾器。但我不確定這是最佳路線。

我不知道如何處理與用戶模型共享的帖子,雖然用戶has_many帖子,但每個帖子可以與多個其他用戶共享。

回答

2

Looks like you need a has_many, :through relation

您卸載user_id不同的表(通過自定義模型,比方說,PostRelation定義),其中列的樣子:
user_id | post_id | kind | created_at | updated_at

您定義的kind列的一種關係(如「視圖','編輯','所有者')和post_iduser_id是不言自明的。

在這種情況下,關係將是:

  • has_many :users, through: :post_relation
  • has_many :post_relations
  • 用戶has_many :posts, through: :post_relation
  • 用戶has_many :post_relations
  • PostRelation belongs_to :user
  • PostRelation belongs_to :post

然後用戶/ posts模型中,你可以定義過濾基礎上,PostRelation地位的帖子自定義的方法:

class Post def editors self.post_relations.includes(:users).where(kind: 'edit') end end

+0

正是我需要的。這很棒 – 2014-10-06 02:11:35

相關問題