【问题标题】:Conditional association with nested form field doesn't validate properly与嵌套表单字段的条件关联未正确验证
【发布时间】:2019-09-17 08:15:51
【问题描述】:

Rails 6.0.0.beta3 红宝石 2.6.1

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

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

end

和变体模型如下:

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

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

问题: 在创建具有variant 的嵌套表单字段的item 时,它会按预期对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】:

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

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

    btw 感兴趣并做了一个最小的测试 repo (https://github.com/localhostdotdev/bug/tree/belongs-to-where-and-accepts-nested-attributes)(虽然没有表格)。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-06-12
      • 2012-11-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多