Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
railsクエリメソッドのselectとpluckの違い

Railsのクエリメソッドのselectpluckは役割が似ているが、それぞれ返り値の型が異なる。

  • selectはActiveRecordが返る
irb(main):285:0* CorporateNumber.where(corporate_number: "H100004").select(:corporate_number)
D, [2016-06-14T17:02:06.443471 #3655] DEBUG -- :   CorporateNumber Load (0.3ms)  SELECT `corporate_numbers`.`corporate_number` FROM `corporate_numbers`  WHERE `corporate_numbers`.`corporate_number` = 'H100004'
=> #<ActiveRecord::Relation [#<CorporateNumber id: nil, corporate_number: "H100004">]>
  • pluckは配列が返る
irb(main):282:0* CorporateNumber.where(corporate_number: "H100004").pluck(:corporate_number)
D, [2016-06-14T17:01:58.253861 #3655] DEBUG -- :    (0.3ms)  SELECT `corporate_numbers`.`corporate_number` FROM `corporate_numbers`  WHERE `corporate_numbers`.`corporate_number` = 'H100004'
=> ["H100004"]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.