2013-08-24 40 views
0

所以我正在一個rails 4應用程序,我有兩個模型的開發人員和應用程序。Rails關係表

基本上我想有一個開發者作爲一個創始人,有多個應用程序以及這些應用程序屬於開發者(創始人)。然後我想要和應用程序有許多合作者和合作者屬於許多應用程序。繼承人我的代碼,是這樣嗎?我會怎麼說添加一個協作者到應用程序?

應用

has_and_belongs_to_many :collaborators, class_name: 'Developer', foreign_key: :collaborator_id 
has_and_belongs_to_many :founders, class_name: 'Developer', foreign_key: :founder_id 

開發

has_and_belongs_to_many :apps, foreign_key: :collaborator_id 
has_and_belongs_to_many :apps, foreign_key: :founder_id 

關係表

def change 
create_table :apps_developers, id: false do |t| 
    t.references :founder, references: 'Developer' 
    t.references :collaborator, references: 'Developer' 

    t.references :app 
    t.boolean :collaborator_pending, default: :true 
end 

add_index :apps_developers, [:founder_id, :app_id], unique: true 
add_index :apps_developers, [:collaborator_id, :app_id, :collaborator_pending], unique: true, name: 'index_apps_collaborators' 
    end 

回答

1

您應該使用合作者HABTM和has_many的創始人,而不是周圍的其他方式。

原因是合作者和應用程序之間的關係是許多對多,而創建者和應用程序之間的關係是一對許多。

/app/models/app.rb

Class App < ActiveRecord::Base 
    belongs_to :founder, :class_name => 'Developer' 
    has_and_belongs_to_many :collaborators, :class_name => 'Developer' 
end 

/app/models/developer.rb

Class Developer < ActiveRecord::Base 
    has_many :apps, :foreign_key => :founder_id 
    has_and_belongs_to_many :apps, :foreign_key => :collaborator_id 
end 

關於你的第二個問題,這是你怎麼能一個合作者添加到應用程式:

app.collaborators << developer 

appApp類和的目的是Developer類的一個對象。

+0

如果可能有不止一個創始人,如共同創始人,這是否可行? – ny95

+0

不可以。但是,你沒有在你的問題中提到這個要求。如果您需要聯合創始人,那麼您在應用程序和創始人之間使用HABTM是正確的。有一件事是肯定的,合作者絕對是HABTM。 – depa

+0

你可以做的另一件事是爲我的答案添加第二個聯合創始人協會。一個應用程序將'belongs_to:co_founder,:class_name =>'Developer''和一個開發者'has_many:apps,:foreign_key =>:co_founder_id'。這樣你就可以使用兩個不同的外鍵,你就可以編寫'app.founder'和'app.co_founder'。 – depa