LoginSignup
1
0

More than 3 years have passed since last update.

nullを条件にしたクエリでデータを取ってくる方法 in ruby and firebase

Last updated at Posted at 2020-04-03

一覧表示させるためにwhereを使う

hogehoge.rb
    def self.all
        list = collection.where("format", "=", null).order(:created_at).get
    end

上記のような形でformatというフィールドにnullを持ったドキュメントを全て持ってくるようなクエリを作るようなコードを書いているつもりなのですが、null部分がundefinedのエラーが出てきてしまい、取得することができなさそうなんですね。

ここの記事には、

Firestore select where a field is null [duplicate]

it is not possible to index on a field that is NOT in the document

と書いてあるし、無理なのかとも思ったんですが、更に下の方には、

However there is a workaround which consists in querying documents that contain properties with a null value data type

とあるので、いけそうでもある。

解決策

rubyではnullってnilで表すんだわ
そう、これですね。ruby上ではnullを扱うにはnilにするのでした。

hogehoge.rb
    def self.all
        list = collection.where("format", "=", nil).order(:created_at).get
    end

とすれば、firebaseからnullを条件にしてドキュメントを取ってくることができました。

おまけ

データを取得してくる時にコレクションに対して、インデックスがないから作れという形でエラーが出ることがあります。

9: The query requires an index. You can create it here: 長ったらしいURL

こんな感じのエラーが出るので、URLをコピペすると、firebaseコンソールに飛び、インデックスを作成するためのダイアログが開くので、ポチッと押してインデックスがビルドされるのを待ってください。ビルドには数分かかります。しばらく経ってまだビルド中みたいになっていてもコンソール自体に更新かけると終わってたりします。

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0