首页 > 解决方案 > RoR 验证依赖模型但如果依赖验证失败则不停止父模型

问题描述

这是一个令人沮丧的简单问题,但它让我很烦恼。

我有两个模型,评论和注释。评论可以有一个或没有注释。注释只有一个文本字段。他们有一个带有accepts_nested_attributes_for字段的共享表单。

目前,每次发表评论时,都会创建一个相关的空白便笺。如果在便笺的文本字段中输入了某些内容,我只想创建便笺。我不想要大量的空白笔记。

我怀疑这是一个微不足道的问题,但如果我能解决它,我该死的。

我试过validates :text, presence: true了,但是,当它失败时,它会阻止创建父评论,这不是想要的。嗯。

note.rb

class Note < ApplicationRecord
    belongs_to :comment
    validates :text, presence: true

评论.rb

class Comment < ApplicationRecord
   ...
  has_one :note, dependent: :destroy
  accepts_nested_attributes_for :note

评论/_form.html.erb

    <%= form.fields_for :note do |note_form| %>
      Notes<br />
      <%= note_form.text_area :text, cols: 57, rows: 8 %>
    <% end %>`

我猜它是在做它应该做的事情。我只是不希望它那样做...对任何可以提供帮助的人来说都是虚拟品脱。

标签: ruby-on-rails

解决方案


新答案。

我查看了您的问题,结果发现accepts_nested_attributes_for [注意该链接适用于rails 6,但与rails 5 相同] 需要其他参数。其中之一是reject_if,这意味着您可以传递一个 proc,如果它返回 false,则嵌套记录将不会保存。

因此,在您的情况下,您可以执行以下操作

# app/models/note.rb
class Note < ApplicationRecord
  belongs_to :comment, optional: true
end

# app/models/comment.rb
class Comment < ApplicationRecord
  has_one :note, dependent: :destroy
  accepts_nested_attributes_for :note, reject_if: proc { |attributes| attributes['text'].blank? }
end

注意,

accepts_nested_attributes_for :note, reject_if: proc { |attributes| attributes['text'].blank? }

如果笔记上的文本为空白,这将返回 false ,从而避免保存空白笔记记录。

我进行了快速测试,这适用于我的 rails 5.2 应用程序。\o/

如果需要sameera207/so-question-58599317,您可以在github上参考我的最低限度的rails应用程序

初步回答,无效

假设这是rails 5,请尝试:inverse_of

更新:optional: true在 OP 评论后添加

class Note < ApplicationRecord
    belongs_to :comment, inverse_of: :notes, , optional: true
    validates :text, presence: true
class Comment < ApplicationRecord
   ...
  has_one :note, dependent: :destroy, inverse_of: :comment
  accepts_nested_attributes_for :note

这是一篇关于 :inverse_of 的非常好的文章,它谈到了accepts_nested_attributes_for,我认为你遇到的问题


推荐阅读