2016-08-28 39 views
1

我想提出一個自加入協會,有兩個關係自加入協會的has_many和belongs_to的(一個)

的has_manybelongs_to的(一個)

我發現2種方式這樣做,但我不知道哪一個更準確,例如在這個答案has_many and belongs_to within same model員工和經理之間有一個關係,經理has_many員工員工belongs_to經理

解決方法是添加一個名爲manager_id的字段,因此如果用戶是經理,那麼manager_id將爲null,如果某個員工的manager_id將爲manager的id。

該協會是這樣的:

has_many :employees, class_name: "User", foreign_key: :manager_id 
belongs_to :manager, class_name: "User", foreign_key: :manager_id 

第二的解決方案,我發現這裏Rails Associations - has_many => :through - but same model 有以下關係:後的has_many related_postsrelated_post belongs_to的發佈

解決方案這裏是創建兩個單獨的表,一個用於posts,一個用於像這樣的related_posts:

create_table "posts", :force => true do |t| 
    t.string "name" 
    t.datetime "created_at" 
    t.datetime "updated_at" 
    end 

    create_table "related_posts", :force => true do |t| 
    t.integer "post_id" 
    t.integer "related_post_id" 
    t.datetime "created_at" 
    t.datetime "updated_at" 
    end 

和協會是這樣的:

class Post < ActiveRecord::Base 
    has_many :related_posts_association, :class_name => "RelatedPost" 
    has_many :related_posts, :through => :related_posts_association, :source => :related_post 
    has_many :inverse_related_posts_association, :class_name => "RelatedPost", :foreign_key => "related_post_id" 
    has_many :inverse_related_posts, :through => :inverse_related_posts_association, :source => :post 
end 

class RelatedPost < ActiveRecord::Base 
    belongs_to :post 
    belongs_to :related_post, :class_name => "Post" 
end 

現在我不知道該往哪個方向走,第一個解決方案看起來簡單,想法是添加其他字段名爲經理標識(或可如果我們與崗位工作),這將是空的所有經理人所POST_ID,我想象一下,與那場,這似乎不正確的空值了很多紀錄......

第二種方案看起來不錯,但在我覺得這是錯誤的東西是關係has_many :inverse_related_posts_association其中s eems like related_post也有其他相關帖子/或者也許一個related_post屬於很多帖子(我不確定)。

在我來說,我想是這樣後的has_many related_posts和related_post belongs_to的(一個)發佈

回答

1

我會去與第一選項,除非你有一個非常引人注目之所以取第二種方法。這很簡單明瞭。而且你可以隨時重構你的代碼。

只要列爲相關所有記錄,在列中有空值沒有什麼特別壞的。在你的情況下,在manager_id中的NULL意味着'這個人沒有經理'。 這裏的NULL值是否相關?我的回答是是的

NULL表示值爲未知無值。 Rails聲明@person.manager.present?將爲經理定義的人正確地返回true,對於沒有經理的人將爲false正確返回。當查看任何特定人員的數據庫記錄時,manager_id字段中的NULL將傳達相同的含義。

+0

在數據庫建模中,第一種選擇是顯而易見的正確方法,但想想在該字段中有數百萬個空值的記錄,聽說有很多空值是一件壞事!相關的所有記錄是什麼意思? – medBo

+0

我在答案中擴展了相關部分,並將在評論中解決其餘問題。 – Baradzed

+0

從體系結構的角度來看,如果表中有許多可爲空的列,並且記錄將被稀疏填充(每個record_預計會有很多NULL),它可能是數據庫設計不好的標誌(首先要考慮的是一些更正常化)。 但這聽起來不是你的情況。 – Baradzed