0

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

在创建帖子之前,我想验证用户是否拥有 aname和 a last_name。另外,如果用户没有name或我想显示一个错误last_name

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

谢谢!

4

1 回答 1

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
于 2013-03-04T21:24:55.120 回答