对表的FROM子句条目的无效引用

时间:2015-06-10 08:25:18

标签: sql ruby-on-rails postgresql

当我想在列表中搜索params并订购时,我有这个错误:

  

错误:对表"客户"

的FROM子句条目的无效引用      

提示:也许您打算引用表别名" customers_contract_periods"。

这是我在rails 4.2.1中的查询: 在我这样做之前:

order = "CONCAT(customers.company_name, customers.last_name)"

和:

contract_periods = ContractPeriod.current
                                 .joins( :contract, :customer )
                                 .merge( Contract.search params[ :search ] )
                                 .select( 'contract_periods.*' )
                                 .where( filter_params )
                                 .reorder( order, :start_on )

和:

contract_periods = contract_periods.merge ContractPeriod.by_state params[ :by_state ] if params[ :by_state ]

contract_periods = contract_periods.paginate( page: params[ :page ],
                                          per_page: params[ :per_page ])


contracts = Contract.includes( :contract_type, :customer )
                    .where( id: contract_periods.map(&:contract_id) )

contract_types = contracts.map( &:contract_type ).uniq
customers = contracts.map( &:customer )

模型关联:

  class Customer < ActiveRecord::Base

  ## Associations
  belongs_to  :billing_address,   class_name: 'Address'
  has_many    :contacts, as: :contactable

  has_many :contracts

class Contract < ActiveRecord::Base

belongs_to :contract_type
belongs_to :customer
has_many   :contract_periods

class ContractPeriod < ActiveRecord::Base

## Associations
belongs_to :contract
has_one    :customer,   through: :contract

1 个答案:

答案 0 :(得分:1)

每当您在查询中引用任何关联的表时,您必须在代码末尾将其称为.references(:contracts)