User.rb模型
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
在创建帖子之前,我想验证用户是否有name
和last_name
。此外,如果用户没有name
或last_name
这些验证是在带回调的模型上执行还是必须在控制器上执行?
谢谢!
答案 0 :(得分: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