2012/04/07

ActiveRecordオブジェクトを そのままハッシュに入れたい時

 ActiveRecord(AR)オブジェクトは
各オブジェクトごとの値を attributes っていうHashで保持しているらしい

  user = User.find_by_user_id(params[:user_id])
  logger.debug(user.to_yaml)#←中身デバッグ

・DEBUGは↓こんな感じ
[DEBUG] --- !ruby/object:User
attributes:
  id: '1'
  name: username
  deleted_at: !!null 
  created_at: '2012-04-07 03:32:09'
  updated_at: '2012-04-07 13:41:55'
changed_attributes: {}
previously_changed: {}
attributes_cache: {}
marked_for_destruction: false
destroyed: false
readonly: false
new_record: false


attributesは
1件しかないARオブジェクトだったら
→ user.attributes

複数取れるARオブジェクトだったら
(プライマリキーで取得できる件数が必ず1件だったとしても find(:all 〜 とかで取得するとこっちになると思われ)
→ user[0..N].attributes

0 件のコメント: