TwitterAppを作成
https://apps.twitter.com/ にアクセス。(電話番号登録されたTwitterアカウントが必要。)
↓
「Create New App」をクリックしてアプリ作成画面へ。
↓
callback URLに「http://192.168.33.11 (もしくは使っているアプリのURL)」を指定しておきます。
↓
必要項目を入力してアプリケーションを作成。
-
Settings
「Allow this application to use ‘Sign in with Twitter」にチェックを入れておくと、二度目のログイン以降は認証画面を省略することができます。 -
Keys and Access Tokens
一番下の『Create my access token』を押して、access tokenを生成する。
このなかから
- Consumer Key (API Key)
- Consumer Secret (API Secret)
- Access Token
- Access Token Secret
を使う。
-
Permissions
今回の目的はツイートですが、権限をを「Read and Write」にしておきます。
gemの追加
gem 'omniauth'
gem 'omniauth-twitter'
gem 'settingslogic'
gem 'twitter', "~> 4.8"
$ bundle install
controllerとmodel作成・route設定
$ rails g model tweet
$ rails g controller tweets index new edit
◯◯_create_tweet.rb
class CreateTweets < ActiveRecord::Migration[5.1]
def change
create_table :tweets do |t|
t.text :text
t.timestamps
end
end
end
tweets_controller.rb
class TweetsController < ApplicationController
require "twitter"
before_action :set_client, only: [:post]
before_action :set_tweet, only: [:edit, :update, :destroy, :post]
def index
@tweets = Tweet.all
end
def new
@tweet = Tweet.new
end
def create
if Tweet.save(tweet_params)
redirect_to tweets_url
else
redirect_to new_tweet_url
end
end
def edit
end
def update
respond_to do |format|
if @tweet.update(tweet_params)
format.html { redirect_to tweets_url, notice: 'Tweet was successfully updated.' }
# format.json { render :show, status: :ok, location: @tweet }
else
format.html { render :edit }
# format.json { render json: @tweet.errors, status: :unprocessable_entity }
end
end
end
def destroy
respond_to do |format|
format.any
if @tweet.destroy
redirect_to tweets_url
format.html { redirect_to tweets_url, notice: 'Tweet was successfully destroyed.' }
else
format.json { head :no_content }
end
end
end
def post
@client.update(@tweet)
redirect_to tweets_url
end
private
def tweet_params
params.require(:tweet).permit(:text)
end
def set_tweet
@tweet = Tweet.find(params[:id])
end
def set_client
@client = Twitter.configure do |config|
config.consumer_key = 'YOUR_CONSUMER_KEY'
config.consumer_secret = 'YOUR_CONSUMER_SECRET'
config.oauth_token = 'YOUR_OAUTH_TOKEN'
config.oauth_token_secret = 'YOUR_OAUTH_TOKEN_SECRET'
end
end
end
config/routes.rb
Rails.application.routes.draw do
resources :tweets, only: [:index, :new, :create, :edit, :update, :destroy] do
collection do
get 'post'
end
end
end
保存したツイート一覧からpostする
app/views/tweets/index.html.erb
<div>
<table>
<thead>
<tr>
<th>ID</th>
<th>Text</th>
<th colspan="3"></th>
</tr>
</thead>
<tbody>
<% @tweets.each do |tweet| %>
<tr>
<td><%= tweet.id %></td>
<td><%= tweet.text %></td>
<% tweet_post_url = 'post?id=' + tweet.id.to_s %>
<td><%= link_to 'Tweet',tweet_post_url, data: { confirm: 'Are you sure?' } %></td>
<td><%= link_to 'Edit', edit_tweet_path(tweet) %></td>
<td><%= link_to 'Destroy', tweet, method: :delete, data: { confirm: 'Are you sure?' } %></td>
</tr>
<% end %>
</tbody>
</table>
</div>