[英]Rails Relation Table
所以我正在開發Rails 4應用程序,並且我有兩個模型Developer和App。
基本上,我希望開發人員充當創始人並擁有多個應用程序,而這些應用程序屬於開發人員(創始人)。 然后,我希望和應用程序有許多協作者,而協作者屬於許多應用程序。 這是我的代碼,對嗎? 我可以怎么說添加協作者到應用程序?
應用程式
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
您應該將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
其中app
是App
類的對象,而developer
是Developer
類的對象。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.