【问题标题】:Rails/Mongoid error messages in nested attributes嵌套属性中的 Rails/Mongoid 错误消息
【发布时间】:2011-07-26 23:05:27
【问题描述】:

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

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 中获取“名称不能为空”消息而不是“联系信息无效”错误消息?

谢谢

【问题讨论】:

标签: validation nested mongoid propagation


【解决方案1】:

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

将这些行添加到用户类

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

【讨论】:

【解决方案2】:

不是返回 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

【讨论】:

    【解决方案3】:

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

      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
    

    【讨论】:

      【解决方案4】:

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

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

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

      这将强制创建contact_info,并在右侧字段触发错误

      如果不添加,不会创建contact_info

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-02-07
        • 2012-08-19
        • 1970-01-01
        • 2012-02-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多