2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

重複したデータを除外するdistinct

Posted at

distinctメソッドの返り値はActiveRecord::Relationオブジェクト

コンソール/catsテーブルの一意のspecies列を取得する
cats_species = Cat.select(:species).distinct
SELECT DISTINCT `cats`.`species` FROM `cats`
user_ids = UserCheckin.pluck(:user_id).uniq

uniqメソッドとは?distinctとの違い

uniqメソッドとは、Railsで取得した重複レコードを1つにまとめるためのメソッドです。
uniqメソッドを実行すると、Railsは内部的にSQLのDISTINCTを実行します。
その他に、uniqメソッドとまったく同じ働きをするdistinctメソッドも存在します。

両者の違いは、

uniqメソッド Rails5以降で非推奨(または使えなくなる)
distinctメソッド Rails5以降で正式メソッド
2
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
2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?