通过多对多关系获取数据

时间:2014-05-19 16:30:12

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

我有3张桌子:

用户类

 User has_many :project_assignments
 User has_many :projects, through: :project_assignments

ProjectAssignment类

 ProjectAssignment  belongs_to :user
 ProjectAssignment  belongs_to :project_owner, class_name: 'User', foreign_key: 'user_creator_id' 
 ProjectAssignment  belongs_to :project

项目

has_many :project_assignments
has_many :users, through: :project_assignments

ProjectAssignment包含以下列:

 project_id, user_id, creator_user_id

我想通过creator_user_id

为用户获取所有项目

ex:current_user.created_projects

查询:ProjectAssignment.where(creator_user_id:current_user.id)

在定义模型中的关系时可以这样做,就像我对projects所做的那样,但foreign_key应该是creator_user_id

2 个答案:

答案 0 :(得分:1)

我认为你只需要在User中使用另外两个关联来利用creator_user_id字段(而不是user.projects将返回用户所属的项目)

试试这个 -

#in User class
has_many :owned_project_assignments, :class_name => "ProjectAssignment", :as => :project_owner, :foreign_key => "user_creator_id"
has_many :owned_projects, :through => owned_project_assignments, :class_name => "Project", :source => :project, :as => :project_owner

:来源和:因为选项可能有点棘手,所以这可能不起作用,它只是我的头顶......

答案 1 :(得分:0)

在我的情况下,这是正确的解决方案:

 has_many :owned_project_assignments, class_name: "ProjectAssignment", foreign_key: 'user_creator_id'
 has_many :owned_projects, through: :owned_project_assignments, source: :project