加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

ruby-on-rails – 嵌套模型上的自定义验证错误

发布时间:2020-12-17 01:58:49 所属栏目:百科 来源:网络整理
导读:class Parent has_one :child accepts_nested_attributes_for :childendclass Child belongs_to :parentend 使用嵌套对象表单,我需要为子模型添加一些额外的验证.这些并不总是在Child上运行,因此我不能将它们放在Child中的验证方法中.在Parent中的validate方
class Parent
  has_one :child
  accepts_nested_attributes_for :child
end
class Child
  belongs_to :parent
end

使用嵌套对象表单,我需要为子模型添加一些额外的验证.这些并不总是在Child上运行,因此我不能将它们放在Child中的验证方法中.在Parent中的validate方法中进行检查似乎是明智的,但是我无法正确添加错误消息.

这确实有效:

class Parent
...
def validate
  errors[ :"child.fieldname" ] = "Don't be blank!"
end

但是我们失去了很好的东西,比如I18n和CSS在错误字段上突出显示.

这不起作用:

def validate
  errors.add :"child.fieldname",:blank
end

解决方法

您应该将它们保存在子模型中,因为这是经过验证的模型,但是,您可以使用if设置条件:并且除非:

class Order < ActiveRecord::Base
  validates :card_number,presence: true,if: :paid_with_card?

  def paid_with_card?
    payment_type == "card"
  end
end

您可以对此进行多种修改,请参阅rails文档http://edgeguides.rubyonrails.org/active_record_validations.html#conditional-validation中的更多内容

我猜你可以添加一个属性,created_by到child,并让Child根据那个选择使用哪些验证.你可以像在答案中那样做:Rails how to set a temporary variable that’s not a database field

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读