我有 2 个模型:
Department
has_many :accounts
Account
belongs_to :department
但我需要以某种方式创建一个具有:
departments_accounts
department_id
account_id
这不是一个多对多表,不是吗?因为一个部门可以有很多账户,但反过来不行。
我应该如何创建将使用迁移设置新表的迁移?
我有 2 个模型:
Department
has_many :accounts
Account
belongs_to :department
但我需要以某种方式创建一个具有:
departments_accounts
department_id
account_id
这不是一个多对多表,不是吗?因为一个部门可以有很多账户,但反过来不行。
我应该如何创建将使用迁移设置新表的迁移?
如果我理解正确,您想在 和 之间创建has_many :through(多对多)关系。Department
Account
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