本文介绍了在Rails ActiveRecord验证期间更改或更新属性值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

摘要:我正在尝试在自定义 ActiveModel :: EachValidator 验证器的内部中更改属性的值.给出以下原型:

Summary: I'm trying to alter an attribute's value within a custom ActiveModel::EachValidator validator. Given the following prototype:

def validate_each(记录,属性,值)

试图设置 value = something 似乎没有任何作用-我是否缺少某些东西?应该有一个聪明的方法来做到这一点...

trying to set value = thing doesn't appear to do anything -- am I missing something? There should be a smart way to do this...

详细信息:我接受输入的URL作为网站的一部分.我不想仅使用URL并直接验证它是否返回了 200 OK 消息,因为这将忽略不是以 http 开头或不以左侧开头的条目排除领先的 www 等.我有一些自定义逻辑来处理这些错误并遵循重定向.因此,如果用户键入 example.org/article 而不是 http://www.example.org/article,我希望验证成功 .该逻辑在验证内正常工作,但是问题是,如果有人在前者中键入内容,则数据库中的存储值将采用错误"形式,而不是经过良好更新的形式.我可以在验证过程中将条目更改为更规范的形式吗?

Detail: I accept a URL input as part of a site. I don't want to just take the URL and directly validate that it returns a 200 OK message, because that would ignore entries that didn't start with http, or left out the leading www, etc. I have some custom logic to deal with those errors and follow redirects. Thus, I'd like the validation to succeed if a user types in example.org/article rather than http://www.example.org/article. The logic works properly inside the validation, but the problem is that if somebody types in the former, the stored value in the database is in the "wrong" form rather than the nicely updated one. Can I change the entry during validation to a more canonical form?

推荐答案

您应该离开验证来执行以下操作: validate ;这不是操作模型属性的正确位置.

You should leave the validation to do just that: validate; it's not the right place to manipulate your model's attributes.

请参见ActiveModel的 before_validation 回调.这是处理模型属性以准备进行验证的更合适的地方.

See ActiveModel's before_validation callback. This is a more appropriate place to be manipulating model attributes in preparation for validation.

看来您至少必须根据.

class YourModel
  extend ActiveModel::Callbacks
  include ActiveModel::Validations
  include ActiveModel::Validations::Callbacks

  before_validation :manipulate_attributes

  def manipulate_attributes
    # Your manipulation here.
  end
end

这篇关于在Rails ActiveRecord验证期间更改或更新属性值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-28 02:39