嵌套包含where语句使用ActiveRecord

时间:2014-08-23 21:37:11

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

我的应用程序的结构如下: ç

lass Project < ActiveRecord::Base
  has_and_belongs_to_many :team_members
  has_one :legal_contract
  has_many :documents
end

class ProjectsTeamMember < ActiveRecord::Base
  belongs_to :project
  belongs_to :team_member
end

class LegalContract < ActiveRecord::Base
  belongs_to :project
end

class TeamMember < ActiveRecord::Base
  has_many :projects_team_members
  has_many :projects, through: :projects_team_members
  has_and_belongs_to_many :projects
end

我正在尝试使用数组中的一个ID找到与legal_contract相关联的所有team_members。尝试包含方法:

  team_members = TeamMember.includes( {projects_team_members: [ { project: :legal_contract} ] } )

我现在想知道我现在如何缩小范围以便只吸引那些人而不是所有人。我试过了

arry= [1,3,5]
team_members = TeamMember.includes( {projects_team_members: [ { project: :legal_contract} ] }).where('legal_contract.id IN', arry)

但收到错误

ActiveRecord::StatementInvalid: PG::SyntaxError: ERROR:  zero-length delimited identifier at or near """"
LINE 1: ...s"."updated_at" AS t0_r6, "projects_team_members"."" AS t1_r...

有谁知道吗?感谢

**更新** 感谢Karlingen

TeamMember.joins(:projects => :legal_contract).where(legal_contracts: { id: [1,3,5] })

2 个答案:

答案 0 :(得分:0)

你需要通过这样的连接来实现这个目标:

TeamMember.joins(:projects => :legal_contract).where(legal_contracts: { id: [1,3,5] }) 

首先,您加入项目表及其法律合同。然后,您搜索具有给定ID的所有合法合同。

请注意,Where子句中的键是以复数形式写的,因为它是表的名称。

答案 1 :(得分:-1)

你需要为projects_team_members设置一个主键,你确定你有一个主键吗?

在尝试查找projects_team_members时,似乎Rails正在创建无效语法:

"projects_team_members".""