CSVでエクスポートしたカスタムフィールドを含めた記事レコードを1行に加工した

Wordpressに入っている記事テーブルをRailsアプリに移行しようとしている。
WPってカスタムフィールド機能があるので、記事とカスタムフィールドのレコードを取り出すのが苦戦した。以下にその思い出綴ります。


以下のSQLは記事で使っているカスタムフィールドを表示する。

SELECT wp_posts.*,wp_posts.guid , wp_term_relationships.*, wp_postmeta.* /* フィールドを指定 */
  FROM wp_posts, wp_term_relationships, wp_postmeta /* テーブルを指定 */
  WHERE wp_posts.ID = wp_term_relationships.object_id and wp_posts.id = wp_postmeta.post_id/* テーブル同士の結びつけ */
  AND wp_term_relationships.term_taxonomy_id = 40 /* カテゴリーIDが40のもの */
  AND wp_posts.post_status = 'publish' /* かつ公開済の記事 */

このSQLの結果では、1つのカスタムフィールドが1レコードとして格納されていて大変扱いにくい。
CSVでエクスポートするとだいたい以下なイメージとなる。

Id, name, meta_key,    meta_value
1 , hoge,  _book,         WEB DB PRESS
1 , hoge,  _created_at ,2012年3月
1 , hoge,  _pen           , ボールペン

この状態からActiveRecordに入れるのは無謀なので、各カスタムフィールドが1行に並ぶように加工するコードを書いた。

# encoding : utf-8
require "csv"

table = CSV.table('park_tango_200.csv')
csv = table.to_a
record_result = []
ids = table[:id].uniq

# カスタムフィールドは複数Postレコードに点在しているので、post_idを起点にイテレーションをする
ids.each do |id|
  temp_hash = nil 
  arcive_hash = Hash.new

  csv.select{|v| v[0] == id}.each do |record|
    temp_hash = Hash[*table.headers.zip(record).flatten] # レコードをハッシュに変換している

    # 投稿
    arcive_hash[:post_title] || arcive_hash.store(:post_title, temp_hash[:post_title])
    arcive_hash[:post_content] || arcive_hash.store(:post_content, temp_hash[:post_content])
    arcive_hash[:id] || arcive_hash.store(:id, temp_hash[:id])
    arcive_hash[:post_date] || arcive_hash.store(:post_date, temp_hash[:post_date])

    # カスタムフィールド
    arcive_hash[:kana] || arcive_hash.store(:kana, temp_hash[:meta_value]) if temp_hash[:meta_key] == "読み"
    arcive_hash[:alias] || arcive_hash.store(:alias, temp_hash[:meta_value]) if temp_hash[:meta_key] == "別名"
    arcive_hash[:mean] || arcive_hash.store(:mean, temp_hash[:meta_value]) if temp_hash[:meta_key] == "標準)〜の意味(〜とは)・〜の実際"
    arcive_hash[:second] || arcive_hash.store(:second, temp_hash[:meta_value]) if temp_hash[:meta_key] == "2つめのコンテンツ"
    arcive_hash[:history] || arcive_hash.store(:history, temp_hash[:meta_value]) if temp_hash[:meta_key] == "固有)〜とは・〜の歴史と今"
    arcive_hash[:assosiate_word] || arcive_hash.store(:assosiate_word, temp_hash[:meta_value]) if temp_hash[:meta_key] == "関連する用語"
    arcive_hash[:i_catch] || arcive_hash.store(:i_catch, temp_hash[:meta_value]) if temp_hash[:meta_key] == "アイキャッチキャプション"
    arcive_hash[:tag] || arcive_hash.store(:tag, temp_hash[:meta_value]) if temp_hash[:meta_key] == "タグ"
    arcive_hash[:thumbnail_id] || arcive_hash.store(:tag, temp_hash[:meta_value]) if temp_hash[:meta_key] == "_thumbnail_id"
  end 

  record_result.push arcive_hash
  temp_hash = nil 
end

あとはActiveRecordでぽこぽこ入れるだけだお

(アイキャッチとれないんですけど、、、)