Rails在哪里加入不同的外键

时间:2013-05-13 15:07:05

标签: ruby-on-rails

我有工作人员和员工表。每个工作订单都分配了一名员工并分配了一名主管。

workorder.rb有:

belongs_to :super, :class_name => "Employee", :foreign_key => "super_id"
belongs_to :employee

我正在尝试使用连接创建where子句。它适用于加入:client。但是,:super不起作用。

这是我目前的尝试:

workorders = workorders.joins(:client,:super).where("wonum like :search or description like :search or clients.client_name like :search or super.employee_full_name like :search ", search: "%#{params[:sSearch]}%")

我回来了:

SELECT COUNT(*) FROM "workorders" INNER JOIN "clients" ON "clients"."id" = "workorders"."client_id" INNER JOIN "employees" ON "employees"."id" = "workorders"."super_id" WHERE (wonum like '%CHUCK%' or description like '%CHUCK%' or clients.client_name like '%CHUCK%' or super.employee_full_name like '%CHUCK%' ) AND (wostatus_id NOT IN (231,230,9263,9264,232))
Completed 500 Internal Server Error in 236ms
ActiveRecord::StatementInvalid - PG::Error: ERROR:  missing FROM-clause entry for table "super"

感谢您的帮助!

1 个答案:

答案 0 :(得分:2)

employees表没有别名为super,在这种情况下根本不需要别名,因为它只加入了一次:

workorders = workorders.joins(:client,:super).
               where("wonum like :search or description like :search or clients.client_name like :search or employees.employee_full_name like :search ", 
               search: "%#{params[:sSearch]}%")

为了您的理智(以及任何阅读此内容的人),请将此逻辑移至范围内:

scope :search, lambda{ |term|
  %w(wonum description clients.client_name employees.employee_full_name).
    map{|field| "#{field} like :search" }.
    join(" or "), search: term
}

workorders = workorders.joins(:client, :super).search("%#{params[:sSearch]}%")