我正在研究具有复杂关联的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
因此,Developer
本身可以有Organization
,而且Developers
可以包含多个has_and_belongs_to_many :organizations
,所以我添加了has_and_belongs_to_many :developers
和User.find().account.developers
来建立这种关系。因此,如果我查找User.find().account.organizations
或App
我获取相关记录,那么一切都可以在我的应用中运行。
现在我们到了遇到麻烦的地方。在我的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
答案 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
。您必须先获得帐户的课程,然后决定使用developers
或organizations