Rails 4:验证存在于 id 或关联之间的区别 [英] Rails 4: Difference between validates presence on id or association

查看:48
本文介绍了Rails 4:验证存在于 id 或关联之间的区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我在模型中有一个belongs_to"关联,我想知道验证关联之间的概念差异:

If I have a 'belongs_to' association in a model, I'd like to know the notional difference between validating an association:

  class Topping  < ActiveRecord::Base
    belongs_to :pancake
    validates  :pancake, presence: true
    ...

并验证关联的模型 ID:

and validating the associated model id:

  class Topping  < ActiveRecord::Base
    belongs_to :pancake
    validates  :pancake_id, presence: true
    ...

动机:

一些为煎饼分配浇头的代码在过去的某个时间停止工作.将验证从关联更改为 id修复"了问题,但我想知道更深层次的原因.

Some code which assigned a topping to a pancake stopped working at some time in the past. Changing the validation from association to id 'fixed' the problem, but I'd like to know the deeper reason why.

(仅供参考,当进入代码时,pancake 是有效的,并且在数据库中,并且顶部对 .pancake.pancake_id 做出了相应的响应.推操作符(pancake.toppings << topping) 和手动分配和保存 (topping.pancake = pancake; topping.save) 因缺少 pancake 验证错误而失败.)

(FYI, when stepping into the code the pancake was valid and in the database and the topping responded to both .pancake and .pancake_id appropriately. Both the push operator (pancake.toppings << topping) and manual assignment and save (topping.pancake = pancake; topping.save) failed with a pancake missing validation error.)

推荐答案

进一步调查,我发现 'presence' 验证器解析为 'add_on_blank':

Investigating further, I found that the 'presence' validator resolves to 'add_on_blank':

http://apidock.com/rails/ActiveModel/Errors/add_on_blank

def add_on_blank(attributes, options = {})
  Array(attributes).each do |attribute|
    value = @base.send(:read_attribute_for_validation, attribute)
    add(attribute, :blank, options) if value.blank?
  end
end

这就是它所说的:如果相关属性为 blank?

This does what it says: adds a validation error if the property in question is blank?

这意味着它只是一个存在检查.所以如果我验证一个 id,那个 id 必须存在.这意味着:

This means it's simply an existence check. So if I validate an id, that id has to exist. That means:

topping.pancake = Pancake.new
topping.valid?

会返回 false.但是:

would return false. However:

topping.pancake_id = -12
topping.valid?

将返回 true.另一方面,如果我验证对象,则正好相反.除非 -12 是有效索引,否则 ActiveRecord 会在收到pancake"消息时自动从数据库加载它.

would return true. On the other hand, if I validate the object the exact opposite would be true. Unless -12 is a valid index, in which case ActiveRecord would automatically load it from the database on receipt of the 'pancake' message.

继续我的问题,进一步调查显示 blank? 委托给 empty?,并且确实有人在上面定义了 empty?煎饼,如果没有浇头则返回 true.

Moving on to my issue, further investigation showed that blank? delegates to empty?, and indeed someone had defined empty? on the pancake, returning true if there are no toppings.

找到了罪魁祸首,并了解了一些有关 Rails 的知识.

Culprit found, and something about Rails learned.

这篇关于Rails 4:验证存在于 id 或关联之间的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆