Ruby-on-rails rails 4 before_validation on::create 或 on::save

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21392960/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 23:17:48  来源:igfitidea点击:

rails 4 before_validation on: :create or on: :save

ruby-on-railsvalidationruby-on-rails-4

提问by andre.orvalho

I am having a case which is getting around my head.

我有一个案子正在绕着我的脑袋。

I have an Image model which I only want to save if it gets uploaded. I also need some information coming from the upload to validate the image(like height and width). But I want only the upload to happen if somebody is trying to save the file the image for the first time.

我有一个图像模型,我只想在上传时保存它。我还需要一些来自上传的信息来验证图像(如高度和宽度)。但我只希望在有人第一次尝试将图像保存文件时上传。

So I thought the best option would be to have a before_validation, but I would like it to run only on save!

所以我认为最好的选择是有一个before_validation,但我希望它只在保存时运行!

My code is on this gist https://gist.github.com/andreorvalho/b21204977d2b70fdef83

我的代码在这个要点上https://gist.github.com/andreorvalho/b21204977d2b70fdef83

So the weird part is this on: :saveand on: :createhave really weird behaviours or at least not what I expected.

所以奇怪的部分是这个on: :save并且on: :create有非常奇怪的行为,或者至少不是我所期望的。

When I put it as on: :saveIf I try to do an image.saveon a test I can see my before_validationcallbacks are not ran!

当我把它当作on: :save如果我尝试做image.save一个测试时,我可以看到我的before_validation回调没有运行!

If I put on: :createis ran in every situation is does not matter if I ran image.save, image.createor image.valid?

如果我on: :create在每一种情况下都跑image.save,我跑也没关系,image.create或者image.valid?

So I am guessing this is either not working or I am misunderstanding the goal of those on settings.

所以我猜这要么不起作用,要么我误解了设置的目标。

p.s. my validation on create, also occurs in every situation save, create or valid?

ps 我在创建时的验证,也发生在保存、创建或有效的每种情况下?

let me know if anybody ran into the same or knows why is not supposed to work like this.

如果有人遇到同样的情况或知道为什么不应该像这样工作,请告诉我。

回答by Jon

The before_validationcallback allows restrictions to particular events within the lifecycle of an object.

before_validation回调允许限制对象的生命周期中的特定事件。

You can use the following syntax:

您可以使用以下语法:

before_validation :set_uuid, on: :create
before_validation :upload_to_system, on: [:create, :update]

Here is the documentation of this option for Rails 4.0, Rails 5.2and Rails 6.0.

这是Rails 4.0Rails 5.2Rails 6.0的此选项的文档。