2015-08-26 88 views
0

我有这样的查询:的ActiveRecord不包括关系

PrimaryModel.includes(:associated_models) 
    .where(foo: true) 
    .where('associated_models.bar >= 0') 

通常情况下,这将促使ActiveRecord的在associated_models加入,而是我得到这个错误:

ActiveRecord::StatementInvalid Exception: PG::UndefinedTable: ERROR: missing FROM-clause entry for table "associated_models"

然而,像这样的查询将正确加入表格:

PrimaryModel.includes(:associated_models) 
    .where(foo: true) 
    .where(associated_models: { baz: true }) 

此外,也许最有说服力的是,工作原理:

PrimaryModel.includes(:associated_models) 
    .where(foo: true) 
    .where(associated_models: { baz: true }) 
    .where('associated_models.bar >= 0') 

在这最后一个, 'associated_models' 得到由.where(associated_models: { baz: true })加入,让.where('associated_models.bar >= 0')才能正常工作。任何人都会遇到这种情况找出解决方案?

回答

1

当你将在查询中使用联想的名字,你试过,你必须明确地说:

PrimaryModel.includes(:associated_models) 
    .where(foo: true) 
    .where('associated_models.bar >= 0') 
    .references(:associated_models) # should be actual table name. 

conditions部分来自DOCO。

但正如你所看到的,当你将它写成Hash语法时,不需要明确提及 - .where(associated_models: { baz: true })

+0

非常好!那就是诀窍。 – nullnullnull