validates_associated不检查关联的存在 [英] validates_associated not checking existence of associations

查看:75
本文介绍了validates_associated不检查关联的存在的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

任何人都可以弄清楚这里发生了什么吗?我能够使我的代码按我想要的方式工作,但是我无法弄清楚为什么validates_associated无法按我期望的那样工作.这是我的代码段:

Can anyone figure out what's going on here? I was able to get my code to work the way I want it to, but I can't figure out why validates_associated isn't working as I expect. Here's a snippet of my code:

class Flag < ActiveRecord::Base
  belongs_to :user
  belongs_to :post

  # allow only one flag per post per user
  validates_uniqueness_of :user_id, :scope => :post_id

  validates :user_id, :post_id, :presence => true
  validates_associated :user, :post

  attr_accessible :user_id, :post_id
end

使用此代码,我无法使用user_id == nil保存标志.我可以保存一个user_id == 12345的标志(即,某些user_id不在数据库中).这就是validates_associated API规范所说的:

With this code I can't save a flag with user_id == nil. I can save a flag with user_id == 12345 (i.e. some user_id not in the database). This is what the validates_associated API specification says:

validates_associated(* attr_names)

validates_associated(*attr_names)

验证关联的一个或多个对象本身是否都是有效的.可与任何类型的关联一起使用.
...
注意:如果尚未分配关联,则此验证不会失败.如果要确保关联既存在又保证有效,则还需要使用validates_presence_of.

Validates whether the associated object or objects are all valid themselves. Works with any kind of association.
...
NOTE: This validation will not fail if the association hasn’t been assigned. If you want to ensure that the association is both present and guaranteed to be valid, you also need to use validates_presence_of.

我可以使用此方法来获得所需的行为,

I was able to get the desired behavior by using this, instead:

  validates :user, :post, :presence => true

我对API规范的理解是validates_associated检查关联的表,以查看是否存在ID与Flag 的外键匹配的行,前提是该外键为非nil .谁能对此提供任何见解?我是否误解了validates_associated应该如何工作?

My understanding of the API specification is that validates_associated checks the associated table to see if a row exists with an id matching the foreign key of Flag provided the foreign key is non-nil. Can anyone offer any insight on this? Am I misunderstanding how validates_associated is supposed to work?

推荐答案

validates_associated只是运行在关联对象的类中指定的验证,它对外键没有任何作用.

validates_associated simply runs the validations that are specified within the associated object's class, it does nothing in regard to foreign keys.

validates :user_id, :presence=>true确保在您的标志记录中存在user_id,仅此而已.

validates :user_id, :presence=>true ensures the presence of a user_id in your flag record, but that's all.

validates :user, :presence=>true用于关联本身,并确保正确设置外键.

validates :user, :presence=>true is used on the association itself and ensures that foreign keys are properly set up.

这篇关于validates_associated不检查关联的存在的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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