14

我有一个这样定义的联系信息类:

class ContactInfo
  include Mongoid::Document

  validates_presence_of :name, :message => ' cannot be blank'

  field :name, :type => String
  field :address, :type => String
  field :city, :type => String
  field :state, :type => String
  field :zip, :type => String
  field :country, :type => String
  embedded_in :user
end

此联系信息类作为嵌套属性嵌入到我的用户类中:

class PortalUser
  include Mongoid::Document
  accepts_nested_attributes_for :contact_info
end

当我尝试保存没有名称的用户时,我收到如下错误消息:

联系方式无效

但是,这对最终用户来说不是很有用,因为他或她不知道哪些联系信息是无效的。REAL 消息应该是“名称不能为空”。但是,此错误不会向上传播。有没有办法在 user.errors 中获取“名称不能为空”消息而不是“联系信息无效”错误消息?

谢谢

4

4 回答 4

14

这是我最终想出的解决方案:

将这些行添加到用户类

after_validation :handle_post_validation
def handle_post_validation
  if not self.errors[:contact_info].nil?
    self.contact_info.errors.each{ |attr,msg| self.errors.add(attr, msg)}
    self.errors.delete(:contact_info)
  end
end
于 2011-03-31T21:11:02.857 回答
1

而不是返回 user.errors.full_messages 为您的用户模型创建一个特定的错误消息方法,您可以在其中处理所有嵌入式文档错误。

class PortalUser
  include Mongoid::Document
  accepts_nested_attributes_for :contact_info
  def associated_errors
    contact_info.errors.full_messages unless contact_infos.errors.empty?
  end
end

在你的控制器中

flash[:error] = user.associated_errors
于 2012-03-21T17:40:22.043 回答
0

我涵盖每个嵌入式文档验证错误的解决方案如下:

  after_validation :handle_post_validation
  def handle_post_validation
    sub_errors = ActiveModel::Errors.new(self)
    errors.each do |e|
      public_send(e).errors.each { |attr,msg| sub_errors.add(attr, msg)}
    end
    errors.merge!(sub_errors)
  end
于 2019-12-04T12:18:59.153 回答
-2

控制器中可能有解决方案...

在创建操作中,您可以添加类似

params[:portal_user][:contact_info_attributes] = {} if params[:portal_user] && params[:portal_user][:contact_info_attributes].nil?

这将强制创建contact_info,并在正确的字段上触发错误

如果不添加,不会创建contact_info

于 2011-04-17T01:35:33.873 回答