与嵌套表单字段的条件关联无法正确验证

问题描述 投票:1回答:1

Rails 6.0.0.beta3 Ruby 2.6.1

我在ItemVariant之间有两个模型关联,如下所示:

class Item < ApplicationRecord
...
  has_many :variants
  accepts_nested_attributes_for :variants,
                                reject_if: :all_blank,
                                allow_destroy: true

end

和Variant模型如下:

class Variant < ApplicationRecord
  belongs_to :item, -> { where(kind: :article) }
end

如上所述,我们有belongs_to的条件关系,它依赖于Item字段kind具有值article

问题:在创建一个item,它有variant的嵌套表单字段时,它会像kind: :article那样提高验证效果,但它会像kind那样提高kind: :novel的所有其他值。在rails控制台上,我尝试手动创建

item = Item.create(kind: :article)
item.variants.create

...

item = Item.create(kind: :novel)
item.variants.create
it raises validation error 'should be of kind: :article only'

它适用于控制台,但不适用于嵌套表单字段。其他相关的已知问题案例:https://github.com/rails/rails/issues/25198

ruby-on-rails validation nested-forms has-many belongs-to
1个回答
0
投票

我建议在Variant模型中验证项目类型,而不是where中的belongs_to

因为在你的情况下Item.create!(kind: :novel).variants.create!引发了一个错误(Item must exist,当我尝试它)。

btw感兴趣并做了一个最小的测试回购(https://github.com/localhostdotdev/bug/tree/belongs-to-where-and-accepts-nested-attributes)(尽管没有形式)。

© www.soinside.com 2019 - 2024. All rights reserved.