简体   繁体   English

在验证创建新对象时获取“ undefined method” ruby​​?

[英]Getting `undefined method` ruby on rails on validation creating new object?

I am following this post and trying to add a validate method before object creation. 我正在关注这篇文章,并尝试在对象创建之前添加一个validate方法。 I keep getting undefined method 'video' for #<Video:0xbe430a0> I am reading this article here http://ruby-for-beginners.rubymonstas.org/ getting to know how ruby works but cannot figure out why I get this error. 我一直在获取undefined method 'video' for #<Video:0xbe430a0>我在这里阅读本文http://ruby-for-beginners.rubymonstas.org/了解ruby的工作原理,但无法弄清楚为什么会出现此错误。

http://api.rubyonrails.org/v5.1/classes/ActiveModel/Validations/ClassMethods.html#method-i-validate http://api.rubyonrails.org/v5.1/classes/ActiveModel/Validations/ClassMethods.html#method-i-validate

If I call new on a ruby object and save it with a validation what do I need to do to the video variable to not get undefined method ? 如果我在ruby对象上调用new并通过验证将其保存,我需要对video变量执行什么操作才能获取undefined method

class Video < ApplicationRecord

  validate :video_count_within_limit, on: :create

  def video_count_within_limit
    if video(:reload).count >= 9
      errors.add(:base, "Exceeded video limit of 9 videos")
    end
  end

as video method actually doesn't exists on your model, and based on post you're following it's actually a reference you should just simple replace video with self . 因为在您的模型上实际上不存在video方法,并且根据发布后的内容,它实际上是一个参考,您应该简单地用self替换video Something like this: if self.reload.count >= 9 errors.add(:base, "Exceeded video limit of 9 videos") end Let me know if this works for you ! 这样的事情:如果self.reload.count> = 9 errors.add(:base,“超出9个视频的视频限制”)end让​​我知道这是否对您有用! Regards 问候


New Answer : 新答案:

On post you're following, they are checking videos as association and then checking if its count bigger then 9. 在您关注的帖子发布后,他们正在检查videos具有关联性,然后检查其计数是否大于9。

How it works is actually is that the main object which is referenced to the videos is not stored to DB but it has videos association so you can check length/count of that. 实际上,它的工作方式是,引用videos的主要对象未存储到数据库,但具有videos关联,因此您可以检查其长度/数量。

In your case, if you're trying to do that on your main object ( Video ) you will get an error that it couldn't be find as it's not persisted but just instantiated as well as your validation method is called before create . 在您的情况下,如果尝试在主对象( Video )上执行此操作,则会得到一个找不到该错误的错误,因为它没有持久化,而是被实例化,并且在create之前调用了验证方法。

This way you're trying to achieve, it's logical only for validating creating some referenced model, which can't be stored has more then 9 videos. 您正尝试通过这种方式来实现,这仅是为了验证创建某些参考模型是合乎逻辑的,而该参考模型无法存储的视频超过9个。

Hope it's clear enough ? 希望足够清楚吗?

Regards 问候

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM