小编Bob*_*ock的帖子

何时使用"validates_associated"v."belongs_to:parent,:validate => true"

似乎在rails中你可以在两个地方定义关联验证,或者在关联本身上:

class Child

  belongs_to :parent, :validate => true

end
Run Code Online (Sandbox Code Playgroud)

或者作为验证回调:

class Child

  belongs_to :parent

  validates_associated :parent

end
Run Code Online (Sandbox Code Playgroud)

这两种方法有什么区别?

测试差异

我想也许前者会创建一个背压,并强制父母只有在孩子有效的情况下才有效:

即(设置时:validate => true)

child.valid? # => false
child.parent.valid? # => also evaluates to false because of the :validate => true condition


# do whatever it takes to make the child valid again
#...
child.valid? # => true
child.parent.valid? # => true
Run Code Online (Sandbox Code Playgroud)

但是我测试了它,但这不会发生.那两种方法之间有什么区别(如果有的话)?

activerecord ruby-on-rails

29
推荐指数
1
解决办法
8236
查看次数

当子类和父类都满足祖父母类型定义时,为什么 mypy 会报告类型不兼容?

给出以下代码:

from typing import Tuple


class Grandparent:
    items: Tuple[str, ...] = ()


class Parent(Grandparent):
    items = ('foo',)


class Child(Parent):
    items = ('foo', 'bar')
Run Code Online (Sandbox Code Playgroud)

mypy报告以下错误:

error: Incompatible types in assignment (expression has type "Tuple[str, str]", base class "Parent" defined the type as "Tuple[str]")
Run Code Online (Sandbox Code Playgroud)

像这样更改代码(在Parent类中再次指定相同的类型)满足mypy

error: Incompatible types in assignment (expression has type "Tuple[str, str]", base class "Parent" defined the type as "Tuple[str]")
Run Code Online (Sandbox Code Playgroud)

鉴于所有位置items的分配都满足相同/原始定义,为什么我需要在类层次结构中的多个位置重新指定相同的类型?items有没有办法避免这样做?

python mypy python-typing

6
推荐指数
1
解决办法
5713
查看次数