0

我正在开发具有复杂关联的 Rails 4 应用程序,但我不知道如何将一个模型加入到父模型中。

基本上我的应用程序逻辑如下

User
  - belongs_to :account, polymorphic: true

Developer
  - has_one :user, as: :account
  - has_and_belongs_to_many :organizations

Organization
  - has_one :user, as: :account
  - has_and_belongs_to_many :developers
  • 我决定通过 STI 走这条路线,因为这使我能够使我的应用程序迁移文件更清晰、更有条理

所以可以有 aDeveloper本身,也可以有 andOrganization包含很多Developers,所以我添加了has_and_belongs_to_many :organizationsandhas_and_belongs_to_many :developers来创建这种关系。因此,如果我查找User.find().account.developersUser.find().account.organizations获取相关记录,我的应用程序中的所有内容都可以正常工作。


现在我们到了我遇到麻烦的部分。在我的 Rails 应用程序中,我有一个名为App. 一个Developer可以Apps自己创建许多,或者一个Developer可以在其中创建Organization和创建许多AppsOrganization所有Developers属于该对象的人也Organization都可以访问。我不知道如何实现这样的关系。有什么建议么?


Developer
  has_one :user, as: :account
  has_many :apps, as: :appable
  has_and_belongs_to_many :founding_organizations, class_name: 'Organization', foreign_key: :founder_id
  has_and_belongs_to_many :collaborating_organizations, class_name: 'Organization', foreign_key: :collaborator_id

  has_and_belongs_to_many :organizations   (Should this stay?)

Organization
       has_one :user, as: :account
  has_many :apps, as: :appable
  has_and_belongs_to_many :founders, class_name: 'Developer', association_foreign_key: :founder_id
  has_and_belongs_to_many :collaborators, class_name: 'Developer', association_foreign_key: :collaborator_id

  has_and_belongs_to_many :developers   (Should this stay?)

App
  belongs_to :appable, polymorphic: true
4

2 回答 2

2

/app/models/app.rb

App < ActiveRecord::Base
  belongs_to :appable, :polymorphic => true
end

/app/models/organization.rb

Organization < ActiveRecord::Base
  has_and_belongs_to_many :founders, :class_name => 'Developer', :association_foreign_key => :founder_id, :join_table => 'founders_organizations'
  has_and_belongs_to_many :collaborators, :class_name => 'Developer', :association_foreign_key => :collaborator_id, :join_table => 'collaborators_organizations'
  has_many :apps, :as => :appable
  # Other relationships
 end

/app/models/developer.rb

Developer < ActiveRecord::Base
  has_and_belongs_to_many :founded_organizations, :class_name => 'Organization', :foreign_key => :founder_id, :join_table => 'founders_organizations'
  has_and_belongs_to_many :collaborated_organizations, :class_name => 'Organization', :foreign_key => :collaborator_id, :join_table => 'collaborators_organizations'
  has_many :apps, :as => :appable
  # Other relationships
 end
于 2013-08-26T01:59:00.087 回答
0

如果你想要一个 HABTM 协会。你需要一个连接表。在 Rails 4 中,您可以添加一个包含以下内容的迁移文件:

create_join_table :developers, :organizations

然后只需使用:

Developer.find().organizations

或者

Organization.find().developers

如果你使用User.find().account. 您必须先获得帐户的课程,然后再决定使用developersorganizations

于 2013-08-26T01:57:57.373 回答