LoginSignup
0
1

More than 5 years have passed since last update.

Rails ActiveRecordでテーブル内に存在する特定の要素の数を知りたい時

Last updated at Posted at 2017-12-14

テーブル内にある特定の要素を取り出す時

たまにあるテーブル内にある要素の取り出し方だと

User.count #or size or length

で行けるけど、住所だったり、カテゴリーだったりある特定の要素に紐付いているデータの数を知りたい時に若干詰まった。

NG
User.find_by(address_id: address_id).count
User.find_by(address_id: address_id).length
User.find_by(address_id: address_id).size

だとmethoderrorになる

OK
User.where(address_id: address_id).count

whereを使いましょう。

0
1
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
0
1