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