2

データベースに、次の属性を含む通知テーブルがありtimestamp:datetimeますread:boolean。私が欲しいのは、通知を照会して注文することです。最初にそれらが読み取られたかどうかによって、次にそれらが取得したタイムスタンプによって、通知の量を10に制限します。

私が試したクエリは次のようになります。

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

これは、ブールフィールドを原因として証明するために絞り込んだエラーを私に与えるだけです。

true / false値で順序付けする既存の方法はありますか、それともTrueとFalseを1と0に変換するある種のカスタムフィールドシリアル化を使用する必要がありますか?

4

1 に答える 1

3

指定したものは、Mongoid 2.4.10、mongo 1.3、rails3.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

test / unit / 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
于 2012-05-29T16:42:17.653 に答える