validate_presence_of父属性mongoid

时间:2013-03-04 20:55:37

标签: ruby-on-rails ruby ruby-on-rails-3 ruby-on-rails-3.2 mongoid

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

在创建帖子之前,我想验证用户是否有namelast_name。此外,如果用户没有namelast_name

,我希望显示错误

这些验证是在带回调的模型上执行还是必须在控制器上执行?

谢谢!

1 个答案:

答案 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