【问题标题】:Mongoid validates_presence_of a belongs_to itemMongoid validates_presence_of a belongs_to 项目
【发布时间】:2014-01-20 02:58:16
【问题描述】:

如何验证定义为 belongs_to 的项目是否存在?换句话说:

class Temp
  include Mongoid::Document
  include Mongoid::Timestamps
  belongs_to :user
end

并且我希望确保输入了用户。

提前致谢!

【问题讨论】:

    标签: ruby activerecord mongoid


    【解决方案1】:

    来自fine manual:

    关系的父文档应该使用has_many宏来表示有n个被引用的子文档,其中被引用的文档使用belongs_to。

    class Band
      include Mongoid::Document
      has_many :members
    end
    
    class Member
      include Mongoid::Document
      field :name, type: String
      belongs_to :band
    end
    

    [...]

    # The parent band document.
    { "_id" : ObjectId("4d3ed089fb60ab534684b7e9") }
    
    # The child member document.
    {
      "_id" : ObjectId("4d3ed089fb60ab534684b7f1"),
      "band_id" : ObjectId("4d3ed089fb60ab534684b7e9")
    }
    

    记下代表belongs_to :band 关系的band_id。这么说:

    belongs_to :user
    

    将field :user_id 隐式添加到您的Temp。这意味着您可以简单地:

    validates_presence_of :user_id
    

    确保已提供:user_id。如果您想确保:user_id 有效,那么您可以:

    validates_presence_of :user
    

    验证将确保temp.user(即User.find(temp.user_id))找到一些东西。

    【讨论】:

    • 最后一部分正是我想要的!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-09-26
    相关资源
    最近更新 更多