뽑아 대 선택

8799 단어 activerecordrails

당기기



Rails에는 선택한 속성 값이 포함된 배열을 반환하는 pluck이 있습니다.

Doctor.pluck(:id)
   (0.9ms)  SELECT "doctors"."id" FROM "doctors"
=> [1, 3, 7, 8, 9, 5]


둘 이상의 속성을 전달하면 pluck은 여러 속성의 배열을 반환합니다.

Doctor.pluck(:id, :updated_at)
   (0.5ms)  SELECT "doctors"."id", "doctors"."updated_at" FROM "doctors"
=> [[1, Wed, 23 Jan 2019 11:44:27.924159000 EST -05:00],
 [3, Tue, 29 Jan 2019 15:47:30.056920000 EST -05:00],
 [7, Thu, 28 May 2020 19:30:29.238601000 EDT -04:00],
 [8, Thu, 28 May 2020 19:30:29.251257000 EDT -04:00],
 [9, Sat, 26 Jun 2021 19:56:41.536687000 EDT -04:00],
 [5, Tue, 28 Jun 2022 16:49:45.091360000 EDT -04:00]]


쿼리는 요청하는 속성만 가져오도록 정확합니다.

SELECT "doctors"."id", "doctors"."updated_at" FROM "doctors"


고르다



선택은 동일한 쿼리를 만듭니다.

Doctor.select(:id, :updated_at)
  Doctor Load (0.3ms)  SELECT "doctors"."id", "doctors"."updated_at" FROM "doctors"

Doctor.pluck(:id, :updated_at)
   (0.3ms)  SELECT "doctors"."id", "doctors"."updated_at" FROM "doctors"



Doctor.select(:id, :updated_at)
  Doctor Load (0.6ms)  SELECT "doctors"."id", "doctors"."updated_at" FROM "doctors"
=>[#<Doctor:0x0000000111a2ec40 id: 1, updated_at: Wed, 23 Jan 2019 11:44:27.924159000 EST -05:00>,
 #<Doctor:0x0000000111a2eab0 id: 3, updated_at: Tue, 29 Jan 2019 15:47:30.056920000 EST -05:00>,
 #<Doctor:0x0000000111a2e998 id: 7, updated_at: Thu, 28 May 2020 19:30:29.238601000 EDT -04:00>,
 #<Doctor:0x0000000111a2e858 id: 8, updated_at: Thu, 28 May 2020 19:30:29.251257000 EDT -04:00>,
 #<Doctor:0x0000000111a2e4c0 id: 9, updated_at: Sat, 26 Jun 2021 19:56:41.536687000 EDT -04:00>,
 #<Doctor:0x0000000111a2e218 id: 5, updated_at: Tue, 28 Jun 2022 16:49:45.091360000 EDT -04:00>]


그러나 select는 호출된 모델의 개체와 함께 ActiveRecord_Relation을 반환합니다.

Doctor.select(:id, :updated_at).class
=> Doctor::ActiveRecord_Relation


그게 다야 여러분 :)

좋은 웹페이지 즐겨찾기