未定义的方法`date'为零:NilClass

时间:2016-10-11 17:58:58

标签: ruby-on-rails

我设置的reminder模型带有" date"列表示事件的日期,"重复"用于指示事件是否重复的列,以及" mail_date"列,用于标记应发送提醒电子邮件的日期。我的模型中有以下内容:

class Reminder < ActiveRecord::Base
  belongs_to :user
  before_save :create_mail_date
  after_create :send_reminder_emails
  extend FriendlyId
  friendly_id :name, use: [:slugged, :finders]

  private

  def create_mail_date
    @reminder.mail_date = @reminder.date - 7.days  <<< ERROR CALLED ON THIS LINE
  end

  def send_reminder_emails
    @reminder.each do |reminder|
        ReminderMailer.reminder_send(reminder.user, reminder).delay(run_at: reminder.mail_date)
        reminder.set_new_dates
    end
  end

  def set_new_dates
    case @reminder.repeating
    when "Weekly"
        @reminder.date = @reminder.date + 1.week
    when "Monthly"
        @reminder.date = @reminder.date + 1.month
    when "Yearly"
        @reminder.date = @reminder.date + 1.year
    end
    @reminder.create_mail_date
  end
end

我得到undefined method日期&#39;对于nil:NilClass error when I try to edit a提醒, which is confirmed by the fact that at this point @reminder comes back as nil . Can anyone help me figure out why this isn't working? Am I supposed to put these methods in the controller? The edit method in the controller is as follows, so @ reminder`在技术上应该定义:

def edit
  @reminder = Reminder.find(params[:id])
  @reminder.save
  render layout: 'nofooter'
end

思想?

3 个答案:

答案 0 :(得分:2)

如果这些方法位于传递了Reminder类实例的控制器中,则@reminder会有意义,由@reminder变量表示。由于您在Reminder类的实例中执行所有工作,因此所有这些@reminder都应该是self。

答案 1 :(得分:0)

@reminder未在您的模型中实例化。它是您在控制器中创建的实例变量。正如Bob在评论中建议的那样,你可以试试self.date。但是,由于您在模型本身内,因此您应该能够执行以下操作:

scala> import scala.util.Try
scala> Try{ "123x".toInt }
res4: scala.util.Try[Int] = Failure(java.lang.NumberFormatException: For input string: "123x")
scala> Try{ "123x".toInt }.isSuccess
res5: Boolean = false

答案 2 :(得分:0)

我在 Ubuntu 20.04

上处理 Rails 4 项目时遇到了类似的问题

我的项目中有两个模型 - ProjectDailyRecord

我试图这样做是为了查看我将获得的数据:

<%= project.daily_records.where(date: project.daily_records.last.date.pluck(:price).sum %>

但是,我收到一个错误:

<块引用>

nil:NilClass 的未定义方法 `date'

我是这样解决的

问题是有些项目目前还没有daily_records的数据,还没有为项目创建每日记录,导致date没有价值,因此返回 nil

我所要做的就是在我的模型的方法中定义它,然后使用 if 条件来检查数据何时为 nil

def daily_records_date
  daily_records = DailyRecord.last.date
  if nil
    return Time.now
  else
    daily_records
  end
end

然后我在我的视图中调用它:

<%= project.daily_records.where(date: project.daily_records_date).pluck(:price).sum %>

我仍然会做一些更改以稍微干一些代码,以及对模型的大部分 db 查询。

仅此而已。

我希望这会有所帮助