Active Record でそれぞれのレコード(行)から特定のカラムの値を取得する方法

結論

attributesメソッドを用いる。

実例

何やかんやと操作して、以下のような形でレコード(行)が取得できたとします(@itemsに入っているものとします)。ここでのモデルクラス名はItemです。

Item(id: integer, item_number: integer, amount: integer, location: string, created_at: datetime, updated_at: datetime)
Item(id: integer, item_number: integer, amount: integer, location: string, created_at: datetime, updated_at: datetime)

この2つのレコードについて、それぞれのレコードのidとそれに対応したlocationを表示するには次のようにします。

@items.each do |item|
  puts "id: #{item.attributes['id']}, location: #{item.attributes['location']}"
end

以下のように表示されて、希望のとおりの値が取得できました。

id: 5, location: 東京
id: 9, location: 京都
Powered by はてなブログ