0

User.rb模型validate_presence_of父屬性mongoid

class User 
    include Mongoid::Document 
    # relationships 
    has_one :post 

    #fields 
    field :name, :type => String 
    field :last_name, :type => String 
end 

Post.rb模型

class Post 
    include Mongoid::Document 

    # relationships 
    belongs_to :user 

    #fields 
    field :title, :type => String 
    field :description, :type => String 

    #validations here 

end 

之前創建一個帖子我想驗證用戶有namelast_name。另外,我想表現出錯誤,如果用戶還沒有namelast_name

這些驗證都與回調的模式進行,或者必須在控制器上執行?

謝謝!

+0

你看了'validates_associated'? – Jesper 2013-03-04 21:20:36

回答

1
class Post 
    include Mongoid::Document 

    # relationships 
    belongs_to :user 

    #fields 
    field :title, :type => String 
    field :description, :type => String 

    #validations here 
    validates_associated :user 
    validate :must_have_name 
    def must_have_name 
    if !(user.present? && (user.name.present? || user.last_name.present?)) 
     errors.add(:user, "add user name") 
    end 
    end 
end 
+0

這不適合我。 post對象被創建並且用戶沒有'name'和'last_name'。我使用的是mongoid id 3.x.謝謝! – hyperrjas 2013-03-04 22:10:49

+0

看起來我所做的與您試圖做的不匹配,所以我更新了我的回覆。 – hwatkins 2013-03-04 22:41:58

+0

現在驗證工作正常,但我無法在我的視圖中看到錯誤。謝謝! – hyperrjas 2013-03-05 14:20:04