ruby-on-rails - rails 用mongoid Model 自关联问题

查看:156
本文介绍了ruby-on-rails - rails 用mongoid Model 自关联问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问 题

mongodb Category Model代码

class Category
  include Mongoid::Document
  include Mongoid::Timestamps

  has_many :childs, :class_name => "Category"
  belongs_to :parent, :class_name => "Category", :foreign_key => "parent_id"
  has_many :commodities

  field :name, type: String
  field :desc, type: String
  field :root, type: Boolean, default: false

  validates :name, presence: true
end

我在rails console 中执行 Category.create!(:name => :商品, :desc => :商品根分类, :root => true)


会报如下错误:

    Mongoid::Errors::Validations:
message:
  Validation of Category failed.
summary:
  The following errors were found: Parent can't be blank
resolution:
  Try persisting the document with valid data or remove the validations.
    from /usr/local/lib/ruby/gems/2.3.0/gems/mongoid-6.0.1/lib/mongoid/persistable.rb:78:in `fail_due_to_validation!'
    from /usr/local/lib/ruby/gems/2.3.0/gems/mongoid-6.0.1/lib/mongoid/persistable/creatable.rb:180:in `block in create!'
    from /usr/local/lib/ruby/gems/2.3.0/gems/mongoid-6.0.1/lib/mongoid/threaded/lifecycle.rb:161:in `_creating'
    from /usr/local/lib/ruby/gems/2.3.0/gems/mongoid-6.0.1/lib/mongoid/persistable/creatable.rb:175:in `create!'
    from (irb):1
    from /usr/local/lib/ruby/gems/2.3.0/gems/railties-5.0.0.1/lib/rails/commands/console.rb:65:in `start'
    from /usr/local/lib/ruby/gems/2.3.0/gems/railties-5.0.0.1/lib/rails/commands/console_helper.rb:9:in `start'
    from /usr/local/lib/ruby/gems/2.3.0/gems/railties-5.0.0.1/lib/rails/commands/commands_tasks.rb:78:in `console'
    from /usr/local/lib/ruby/gems/2.3.0/gems/railties-5.0.0.1/lib/rails/commands/commands_tasks.rb:49:in `run_command!'
    from /usr/local/lib/ruby/gems/2.3.0/gems/railties-5.0.0.1/lib/rails/commands.rb:18:in `<top (required)>'
    from bin/rails:4:in `require'
    from bin/rails:4:in `<main>'
    

如何解决这种自关联的问题,外键创建的时候设置成空.

解决方案

我已经找到答案了, mongoid的官方文档并没有明确给出来,真是醉了,
mongoid关联有一个optional选项, 把关联的字段添加上这个选项后如下面这样就可以了

belongs_to :parent, :class_name => "Category", :foreign_key => "parent_id",optional: true

这篇关于ruby-on-rails - rails 用mongoid Model 自关联问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆