我在 Rails 日志中得到以下信息:
NoMethodError (undefined method `employee' for nil:NilClass):
app/datatables/workorders4_datatable.rb:16:in `as_json'
app/controllers/workorders_controller.rb:92:in `block (2 levels) in index8'
app/controllers/workorders_controller.rb:90:in `index8'
这是 workorders4_datatable 代码:
class Workorders4Datatable
delegate :params, :h, :link_to, :number_to_currency, to: :@view
def initialize(view)
@view = view
end
def mygroupsopenwos(employee)
workorders.select("workorders.*").joins("left outer join empgroups ON empgroups.workgroup_id=workorders.workgroup_id").where("empgroups.employee_id = ?", employee).where("wostatus_id NOT IN (?)", [231, 230, 9263, 9264, 232] )
end
def as_json(options = {})
{
sEcho: params[:sEcho].to_i,
iTotalRecords: mygroupsopenwos(User.current.employee.id).count,
iTotalDisplayRecords: mygroupsopenwos(User.current.employee.id).total_entries,
aaData: data
}
end
private
def data
mygroupsopenwos(User.current.employee.id).map do |workorder|
[
link_to(workorder.wonum, workorder),
h(workorder.parent.try(:wonum)),
h(workorder.workgroup.try(:group_name)),
h(workorder.employee.try(:last_name)),
h(workorder.description),
h(workorder.type.try(:typecode)),
h(workorder.location.try(:name)),
h(workorder.woasset.try(:assetnum)),
h(workorder.wostatus.try(:statuscode)),
h(workorder.priority)
]
end
end
def workorders
@workorders ||= fetch_workorders
end
def fetch_workorders
workorders = Workorder.order("#{sort_column} #{sort_direction}")
workorders = workorders.page(page).per_page(per_page)
if params[:sSearch].present?
workorders = workorders.includes(:wostatus,:employee,:client,:type,:location).where("wonum ILIKE :search or workorders.description ILIKE :search or wostatuses.statuscode ILIKE :search or employees.last_name ILIKE :search or employees.first_name ILIKE :search or clients.client_name ILIKE :search or types.typecode ILIKE :search or locations.name ILIKE :search", search: "%#{params[:sSearch]}%")
end
workorders
end
def page
params[:iDisplayStart].to_i/per_page + 1
end
def per_page
params[:iDisplayLength].to_i > 0 ? params[:iDisplayLength].to_i : 10
end
def sort_column
columns = %w[workorders.wonum workorders.parent_id workorders.workgroup_id workorders.employee_id workorders.description workorders.type_id workorders.location_id workorders.woasset_id workorders.wostatus_id workorders.priority]
columns[params[:iSortCol_0].to_i]
end
def sort_direction
params[:sSortDir_0] == "desc" ? "desc" : "asc"
end
end
这行代码试图获取员工:
h(workorder.employee.try(:last_name)),
我正在使用 TRY - 那么为什么会出现错误?
谢谢你的帮助!!