2

我正在使用 Railscast 的一种方法来远程访问 dataTables 的表。

这是 workorders4_datatable.rb 中代码的开始:

class Workorders4Datatable

delegate :params, :h, :link_to, :number_to_currency, to: :@view

def initialize(view)
  @view = view
end

def as_json(options = {})
  {
      sEcho: params[:sEcho].to_i,
      iTotalRecords: Workorder.external.count,
      iTotalDisplayRecords: workorders.external.total_entries,
      aaData: data
  }
end

private

def data
  workorders.external.map do |workorder|
    [
        link_to(workorder.id, workorder),
        h(workorder.parent.try(:id)),
        h(workorder.description),
        h(workorder.client.try(:client_name)),
        h(workorder.woasset.try(:assetnum)),
        h(workorder.type.try(:typecode)),
        h(workorder.billmethod.try(:method_name)),
        h(workorder.workgroup.try(:group_name)),
        h(workorder.employee.try(:employee_full_name)),
        h(workorder.wostatus.try(:statuscode)),
        h(workorder.expenses.tobill.sum("quantity") * workorder.expenses.sum("unitcost")),
        h(workorder.events.tobill.sum("hours")),
        h(workorder.events.sum("hours")),
        link_to('ADD Invoice', new_invoice_path(:workorder_id => workorder), :class => 'btn btn-primary')
    ]
  end
end

除了这一行之外,所有这些都有效:

link_to('ADD Invoice', new_invoice_path(:workorder_id => workorder), :class => 'btn btn-primary')

它会导致此错误:

NoMethodError - undefined method `new_invoice_path' for #<Workorders4Datatable:0x007f94513588a0>:

然而,以下工作以不同的观点起作用:

<%= link_to 'ADD Invoice', new_invoice_path(:workorder_id => @workorder.id), :class => 'btn btn-primary' %>

有什么办法可以让它工作吗?

4

1 回答 1

6

你试过用 替换new_invoice_path@view.new_invoice_path?那可能行得通。原因是因为new_invoice_path应该在 的上下文中调用view,但它是在 . 的上下文中调用的Workorders4Datatable

我过去曾将这种模式视为一种捷径:

def v
  @view
end

v.new_invoice_path
于 2013-10-04T21:28:03.610 回答