ruby-on-rails-3.1 - Mongoid order_by bool 值

标签 ruby-on-rails-3.1 mongoid mongodb-ruby

我的数据库中有一个通知表,其中包含属性:timestamp:datetimeread:boolean。我想要的是查询和订购我的通知;首先是它们是否被读取,然后是它们获得的时间戳,然后将通知数量限制为 10。

我尝试过的查询看起来像这样:

@user.notifications.order_by([[:read,:desc],[:timestamp,:desc]]).limit(10)

这只给了我一个错误,我将其范围缩小到证明 bool 字段是罪魁祸首。

是否存在按真/假值排序的现有方法,或者我应该诉诸使用某种自定义字段序列化将 True 和 False 转换为 1 和 0?

最佳答案

您指定的内容适用于 Mongoid 2.4.10、mongo 1.3、rails 3.2.3。希望以下内容能够帮助解决您的问题。

class User
  include Mongoid::Document

  field :name, type: String
  has_many :notifications
end

class Notification
  include Mongoid::Document

  field :read, type: Boolean
  field :timestamp, type: DateTime
  belongs_to :user
end

测试/单元/notification_test.rb

require 'test_helper'

class NotificationTest < ActiveSupport::TestCase
  def setup
    User.delete_all
    Notification.delete_all
  end

  test "order_by boolean" do
    @user = User.create(name: 'Gary')
    [
      [true, 1.day.ago], [false, 2.days.ago], [false, 3.days.ago], [true, 5.days.ago], [false, 8.days.ago], [true, 11.days.ago],
      [false, 4.days.ago], [true, 6.days.ago], [true, 7.days.ago], [false, 9.days.ago], [false, 10.days.ago]
    ].each do |read, timestamp|
      @user.notifications << Notification.create(read: read, timestamp: timestamp)
    end
    assert_equal(1, User.count)
    assert_equal(11, Notification.count)
    result = @user.notifications.order_by([[:read,:desc],[:timestamp,:desc]]).limit(10).to_a
    assert_equal(10, result.size)
    result.each do |r|
      p [r.read, r.timestamp]
    end
  end
end

测试输出

Run options: --name=test_order_by_boolean

# Running tests:

[true, Mon, 28 May 2012 12:33:49 -0400]
[true, Thu, 24 May 2012 12:33:49 -0400]
[true, Wed, 23 May 2012 12:33:49 -0400]
[true, Tue, 22 May 2012 12:33:49 -0400]
[true, Fri, 18 May 2012 12:33:49 -0400]
[false, Sun, 27 May 2012 12:33:49 -0400]
[false, Sat, 26 May 2012 12:33:49 -0400]
[false, Fri, 25 May 2012 12:33:49 -0400]
[false, Mon, 21 May 2012 12:33:49 -0400]
[false, Sun, 20 May 2012 12:33:49 -0400]
.

Finished tests in 0.023062s, 43.3614 tests/s, 130.0841 assertions/s.

1 tests, 3 assertions, 0 failures, 0 errors, 0 skips

关于ruby-on-rails-3.1 - Mongoid order_by bool 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8295857/

相关文章:

mongodb - 使用 MongoDB 按函数嵌套分组

ruby - 使用 SSL 通过 Ruby 驱动程序连接到 Mongod 返回 Mongo::ConnectionFailure

ruby-on-rails - 使用 mongo-ruby-driver 进行文档更新?

postgresql - Rails 3.1 - 推送到 Heroku - 安装 postgres 适配器时出错?

ruby-on-rails-3.1 - 由于新的遗物错误,Rails 服务器无法启动

mysql - Heroku 上的设置数据库是什么?

ruby-on-rails - 在 Rails 中使用 Mongoid 的 MongoDB - 地理空间索引

ruby-on-rails-3.1 - i18n 格式化文本

mongoid - 通过Tire(mongoid4,rails4)插入新文档后,Elasticsearch映射未更新

mongodb - 有没有办法将整个mongodb集合转储到oplog中?