【问题标题】:NoMethodError: undefined method `created_at' for nil:NilClassNoMethodError: nil:NilClass 的未定义方法“created_at”
【发布时间】:2019-01-04 13:26:50
【问题描述】:

所以我在 rails 模型中玩范围。

这些查询在开发环境中完美运行,但在生产环境中无法正常运行。

这是我的 Fee 模型,我从中触发 active-record 查询以从 StudentFeeInvoice 模型获取特定发票。

app/models/fee.rb

most_recent_invoice = aStudent.student_fee_invoices.invoices_except_pending_and_adjusted.order(:created_at).last
new_filter_for_invoices = aStudent.student_fee_invoices.invoices_after_specific_date(most_recent_invoice.created_at)"

app/model/student_fee_invoice.rb

scope :invoices_except_pending_and_adjusted, -> {where("status != ? AND status != ?", "Pending", "Adjusted")}
scope :invoices_after_specific_date, -> (created_date) {where('created_at > ?', created_date)}

请纠正我做错了什么。 提前致谢!

【问题讨论】:

  • 如果有人要求上下文进一步解释以建立理解,我很乐意解释。

标签: ruby-on-rails activerecord rails-activerecord


【解决方案1】:

很可能,aStudent.student_fee_invoices.invoices_except_pending_and_adjusted.order(:created_at).last 正在返回nil

在这种情况下,您将需要以下内容:

new_filter_for_invoices = aStudent.student_fee_invoices.invoices_after_specific_date(most_recent_invoice ? most_recent_invoce.created_at : DateTime.now)

【讨论】:

  • 爱你@Roc Khalil ...!
  • 你避免了错误并将日期转移到DateTime.now,但你确定这个日期对他进一步的逻辑实现有意义吗?
  • 实际上我使用 new_filter_for_invoices 作为标志,如果它的“0”我希望不执行块的下一个代码。那么这个 new_filter_for_invoices = aStudent.student_fee_invoices.invoices_after_specific_date(most_recent_invoice.created_at)" 如果 new_filter_for_invoices.present 呢?
猜你喜欢
  • 1970-01-01
  • 2013-11-14
  • 2013-01-14
  • 2017-10-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多