在Rails中被命名为多个关系

时间:2013-05-27 18:20:22

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

我应该如何在Rails 3.2中创建以下模型?项目可以有1个以上的所有者和1个以上的用户。它们都是Person类的实例。我考虑过has_and_belongs_to_many,但我不知道如何为每个项目处理两个单独的人员集合。

3 个答案:

答案 0 :(得分:0)

您需要一个联接模型来表示每个has-and-belongs-to-many关系,并且您将使用here所述的has-many-through进行访问:

class ProjectOwnerLink < ActiveRecord::Base
  belongs_to :project
  belongs_to :owner, class_name: 'Person'
end

class ProjectUserLink < ActiveRecord::Base
  belongs_to :project
  belongs_to :user, class_name: 'Person'
end

class Project < ActiveRecord::Base
  has_many :project_owner_links
  has_many :owners, :through => :project_owner_links
  has_many :project_user_links
  has_many :users, :through => :project_user_links
end

class Person < ActiveRecord::Base
  has_many :project_owner_links
  has_many :owned_projects, :through => :project_owner_links, :source => :project
  has_many :project_user_links
  has_many :used_projects, :through => :project_user_links, :source => :project
end

答案 1 :(得分:0)

您可以定义另一个模型Participation,它保存关系的类型,即用户的角色。 (未经测试)代码:

class Project < ActiveRecord::Base
  has_many :participations
  has_many :users, :through => :participations

  def with_role(role)
    includes(:participations).where('participation.role = ?', role)
  end

  def owners
    users.with_role('owner')
  end

  def participants
    users.with_role('participant')
  end
end

class User < ActiveRecord::Base
  has_many :participations
  has_many :projects, :through => :participations

  def with_role(role)
    includes(:participations).where('participation.role = ?', role)
  end

  def projects_owned
    projects.with_role('owner')
  end

  def projects_participating_in
    projects.with_role('participant')
  end
end

class Participation < ActiveRecord::Base
  # has an attribute 'role'

  belongs_to :project
  belongs_to :user
end

答案 2 :(得分:0)

以下是演示应用程序。

https://github.com/diatmpravin/habtm-demo.git

请看看,如果您有任何疑问,请与我联系?