如何从模型中的 lambda 内部访问 Rails 错误数组?

发布于 2024-11-16 06:19:00 字数 393 浏览 0 评论 0原文

我正在尝试访问错误数组以显示在我的视图中,但我正在模型内的 lambda 内写入它。我不断收到:

NameError Exception: undefined local variable or method `errors'

这是我的模型代码

accepts_nested_attributes_for :entries,
  :reject_if => lambda {
    "validation here"
    errors[:base] = "You can't do that" #this line raises the above error
  }

在 lambda 之外(在模型本身中),错误正常工作。

I'm trying to access the errors array to display in my view, but I'm writing to it inside a lambda within the model. I keep getting:

NameError Exception: undefined local variable or method `errors'

Here's my code for my model

accepts_nested_attributes_for :entries,
  :reject_if => lambda {
    "validation here"
    errors[:base] = "You can't do that" #this line raises the above error
  }

Outside of the lambda (in the model itself), the errors work correctly.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

我很OK 2024-11-23 06:19:00

当您设置该值时,您必须在此处使用 self.

accepts_nested_attributes_for :entries,
  :reject_if => lambda {
    "validation here"
    self.errors[:base] = "You can't do that" #this line raises the above error
  }

As you're setting the value, you'll have to use self. here

accepts_nested_attributes_for :entries,
  :reject_if => lambda {
    "validation here"
    self.errors[:base] = "You can't do that" #this line raises the above error
  }
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文