Permalink
Browse files

Add csv import

  • Loading branch information...
twata701 committed Feb 16, 2014
1 parent b0bef04 commit 359c78f8f90a56a8e399332c951cc8b388f817e7
@@ -1,3 +1,5 @@
# coding: utf-8
class TweetsController < ApplicationController
before_action :set_tweet, only: [:show, :edit, :update, :destroy]
@@ -60,7 +62,24 @@ def destroy
format.json { head :no_content }
end
end
# GET /tweets/import_csv_new
def import_csv_new
end
# POST /tweets/import_csv
def import_csv
respond_to do |format|
if Tweet.import_csv(params[:csv_file])
format.html { redirect_to tweets_path }
format.json { head :no_content }
else
format.html { redirect_to tweets_path, :notice => "CSVファイルの読み込みに失敗しました。" }
format.json { head :no_content }
end
end
end
private
# Use callbacks to share common setup or constraints between actions.
def set_tweet
View
@@ -1,2 +1,40 @@
# coding: utf-8
require 'csv' # csv操作を可能にするライブラリ
require 'kconv' # 文字コード操作をおこなうライブラリ
class Tweet < ActiveRecord::Base
def self.import_csv(csv_file)
# csvファイルを受け取って文字列にする
csv_text = csv_file.read
# 読み込む前に古いツイートをすべて削除する。
Tweet.delete_all
#文字列をUTF-8に変換
CSV.parse(Kconv.toutf8(csv_text)) do |row|
# ヘッダー行を回避するためにtweet_idが数値でない場合は読み飛ばす
if row[0] =~ /\d+/
tweet = Tweet.new
tweet.tweet_id = row[0]
tweet.in_reply_to_status_id = row[1]
tweet.in_reply_to_user_id = row[2]
tweet.timestamp = row[3]
tweet.source = row[4]
tweet.text = row[5]
tweet.retweeted_status_id = row[6]
tweet.retweeted_status_user_id = row[7]
tweet.retweeted_status_timestamp = row[8]
tweet.expanded_urls = row[9]
tweet.save
end
end
return true
end
end
@@ -0,0 +1,5 @@
<h1>Import tweets CSV File</h1>
<%= form_tag('import_csv', :method => 'post', :multipart => true, :class => 'navbar-form pull-left') do %>
<%= file_field_tag(:csv_file) %>
<%= submit_tag("CSV Import",:class => 'btn') %>
<% end %>
@@ -1,6 +1,6 @@
<h1>Listing tweets</h1>
<table>
<table class="table">
<thead>
<tr>
<th>Tweet</th>
View
@@ -1,5 +1,10 @@
Twice::Application.routes.draw do
resources :tweets
resources :tweets do
collection do
get 'import_csv_new'
post 'import_csv'
end
end
# The priority is based upon order of creation: first created -> highest priority.
# See how all your routes lay out with "rake routes".

0 comments on commit 359c78f

Please sign in to comment.