2011-03-31 122 views
12

我有這樣定義的聯繫人信息類Mongoid錯誤消息:軌道/嵌套屬性

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中的'名稱不能爲空'消息,而不是'聯繫信息無效'的錯誤信息?

感謝

+0

蒙戈有這個內置的,validates_associated。請參閱http://stackoverflow.com/questions/5078661/field-for-and-nested-form-with-mongoid – 2012-09-25 21:59:29

+1

validates_associated只驗證關聯的模型,但它仍然吐出無用的錯誤消息。 – UrLicht 2013-09-16 21:43:53

回答

11

這是我最終想出瞭解決方案:

增加這些線路和用戶類

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 
+0

Mongo具有內置的'validates_associated'。請參閱http://stackoverflow.com/questions/5078661/field-for-and-nested-form-with-mongoid – 2012-09-25 21:59:16

+0

請注意,此代碼會將嵌套屬性添加到錯誤數組的末尾。 – Nobu 2014-02-11 22:35:59

-2

有可能是在控制器的解決方案......

在創建動作中你可以添加類似於

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

這將迫使contact_info創造,將觸發右外場

錯誤如果不加這個,不創建

1

contact_info代替返回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