Rails has_and_belongs_to_many with Many

时间:2013-08-26 01:26:48

标签: ruby-on-rails activerecord ruby-on-rails-4 activemodel

我正在研究具有复杂关联的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走这条路,因为这样可以让我的应用程序迁移文件更清洁,更有条理

因此,Developer本身可以有Organization,而且Developers可以包含多个has_and_belongs_to_many :organizations,所以我添加了has_and_belongs_to_many :developersUser.find().account.developers来建立这种关系。因此,如果我查找User.find().account.organizationsApp我获取相关记录,那么一切都可以在我的应用中运行。


现在我们到了遇到麻烦的地方。在我的Rails应用程序中,我有一个名为Developer的模型。 Apps可以自行创建多个Developer,或者Organization可以创建Apps并在Organization内创建许多Developers所有属于该Organization的{​​{1}}也可以访问。我不知道如何实现这样的关系。有什么建议吗?


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

2 个答案:

答案 0 :(得分: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

答案 1 :(得分:0)

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

create_join_table :developers, :organizations

然后使用:

Developer.find().organizations

Organization.find().developers

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