2013-11-03 25 views
-1

我有2種型號:如何創建一個1關聯和遷移:很多

Department 
has_many :accounts 

Account 
belongs_to :department 

但我需要以某種方式創建一個具有表:

departments_accounts 
department_id 
account_id 

這不是一個多對多的表雖然是嗎?由於一個部門可以有多個帳戶,但不是相反。

我應該如何創建一個使用遷移來設置新表的遷移?

回答

1

如果我理解正確,您希望在DepartmentAccount之間創建has_many :through(多對多)關係。

rails g model DepartmentAccount department:references account:references 

這將創建一個模型DepartmentAccount與關聯:

belongs_to :department 
belongs_to :account 

而且你必須改變你的Department模式對

has_many :department_accounts 
has_many :accounts, through: :department_accounts 

而且Account模型需要有

has_many :department_accounts 
has_many :departments, through: :department_accounts