2

我有实现的类

module CanBePublished

  def self.included(o)
    o.class_eval do
      field :public, type: Boolean, default: false
      scope :published, -> { where(public: true) }
    end
  end

end  

查看控制台会话中发生的情况:

[1] pry(main)> Portfolio.published.first
=> nil
[2] pry(main)> Portfolio.first
=> #<Portfolio _id: 5391fbc5c1e3dfcf02000001, index: -1, public: "1", title: "test", _slugs: ["test"], description: "portfolio *description*">
[3] pry(main)> Portfolio.where(public: 1)
=> #<Mongoid::Criteria
  selector: {"public"=>true}
  options:  {}
  class:    Portfolio
  embedded: false>

[4] pry(main)> Portfolio.where(public: true)
=> #<Mongoid::Criteria
  selector: {"public"=>true}
  options:  {}
  class:    Portfolio
  embedded: false>

[5] pry(main)> Portfolio.where(public: "1")
=> #<Mongoid::Criteria
  selector: {"public"=>true}
  options:  {}
  class:    Portfolio
  embedded: false>

正如 [1] 所有这些查询都返回 nil。[2] 表明存在一个应该从查询返回的现有对象。

似乎查询总是使用布尔子句正确翻译,但在数据库中,该值作为字符串保留,因此与布尔值不匹配(我的印象)。

[36] pry(main)> p1 = Portfolio.create({title: 'with params', public: '1'})
=> #<Portfolio _id: 53922082c1e3dfebb9000002, index: -1, public: "1", title: "with params", _slugs: ["with-params"], description: nil>
[38] pry(main)> p1.save
=> true
[39] pry(main)> p1.public == true
=> false

不知何故,mongoid 或 mongo 并没有将“1”转换为应有的真值。

[40] pry(main)> p2 = Portfolio.create({title: 'with params2', public: true})
=> #<Portfolio _id: 5392211ec1e3dfebb9000003, index: -1, public: true, title: "with params2", _slugs: ["with-params2"], description: nil>
[41] pry(main)> p2.save
=> true
[42] pry(main)> p2.public == true
=> true

mongod --version 数据库版本 v2.6.1

mongoid 4.0.0

4

0 回答 0