Rails 6.0.0.beta3 Ruby 2.6.1
我在Item
和Variant
之间有两个模型关联,如下所示:
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
我建议在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)(尽管没有形式)。