将我的控制器中的方法(Invoices
)移动到相应的模型中,我遗漏了一些东西。我已尝试关注this和this甚至是this,并且我遇到了一些我需要额外关注的小问题。
我的工作控制器方法就是这样。
def array_of_disbursable_invoices
sql = "SELECT MIN(departure_date), ch_invoice.invoice_id
FROM ch_invoice
INNER JOIN ch_trip
ON ch_invoice.invoice_id = ch_trip.invoice_id
WHERE departure_date <= (SELECT SYS_EXTRACT_UTC(SYSTIMESTAMP)FROM DUAL)
AND service_rendered = 0
AND paid = 1
Group By ch_invoice.invoice_id"
report = ActiveRecord::Base.connection.exec_query(sql)
render json: report
end
我正试图把它变成这个。
def array_of_disbursable_invoices
report = report.array_of_disbursable_invoices
render json: report
end
我的模型中有逻辑。
def array_of_disbursable_invoices
sql = "SELECT MIN(departure_date), ch_invoice.invoice_id
FROM ch_invoice
INNER JOIN ch_trip
ON ch_invoice.invoice_id = ch_trip.invoice_id
WHERE departure_date <= (SELECT SYS_EXTRACT_UTC(SYSTIMESTAMP)FROM DUAL)
AND service_rendered = 0
AND paid = 1
Group By ch_invoice.invoice_id"
ActiveRecord::Base.connection.exec_query(sql)
end
当前错误消息
未定义的方法`array_of_disbursable_invoices'为nil:NilClass
答案 0 :(得分:1)
你打败了我(基本上,我的第二个选择)。但是,无论如何我都会发布这个。
执行此操作时:
def array_of_disbursable_invoices
report = report.array_of_disbursable_invoices
render json: report
end
您在实例上调用array_of_disbursable_invoices
。但是,您没有实例化Report
- 因此,undefined method 'array_of_disbursable_invoices' for nil:NilClass
错误。
所以,我认为你有两个选择:
(1)您可以在实例上调用该方法,例如:
report = Invoice.new.array_of_disbursable_invoices
(2)您可以将该方法设为类方法,例如:
class Invoice < ActiveModel::Base
class << self
def array_of_disbursable_invoices
sql = "SELECT MIN(departure_date), ch_invoice.invoice_id
FROM ch_invoice
INNER JOIN ch_trip
ON ch_invoice.invoice_id = ch_trip.invoice_id
WHERE departure_date <= (SELECT SYS_EXTRACT_UTC(SYSTIMESTAMP)FROM DUAL)
AND service_rendered = 0
AND paid = 1
Group By ch_invoice.invoice_id"
connection.exec_query(sql)
end
end
end
我想我推荐(1)。另外,就个人而言,我使用ActiveRecord查询接口而不是SQL(假设您在模型中设置了所有关联)。但是,这是个人偏好。
答案 1 :(得分:0)
在控制器中使用以下代码。
def array_of_disbursable_invoices
report = Invoice.array_of_disbursable_invoices
render json: report
end
这在模型中。
def self.array_of_disbursable_invoices
sql = "SELECT MIN(departure_date), ch_invoice.invoice_id
FROM ch_invoice
INNER JOIN ch_trip
ON ch_invoice.invoice_id = ch_trip.invoice_id
WHERE departure_date <= (SELECT SYS_EXTRACT_UTC(SYSTIMESTAMP)FROM DUAL)
AND service_rendered = 0
AND paid = 1
Group By ch_invoice.invoice_id"
ActiveRecord::Base.connection.exec_query(sql)
end