LoginSignup
2
4

More than 5 years have passed since last update.

railsでapiを使ってtwitterフォロー機能を作る

Last updated at Posted at 2018-03-17

仕様

  • twitter apiを使って任意のユーザーのフォロー機能を作る。
  • ruby on rails

urlじゃなくてapiを使うのはcontrollerで複数の処理を行い、その処理の中でフォローをするという機能を作りたいため。

twitter OmniAuthでログイン機能を作る

「OmniAuthを利用して、Twitterログイン機能を作る【初心者向け】」
https://qiita.com/To_BB/items/01863aa50d628c069b64

twitter apiはOmniAuthで認証されていないと使えないので上記の記事を元に実装

twitter gem追加

gem 'omniauth'
gem 'omniauth-twitter'
gem 'twitter'

controllerにフォロー機能追加

class PostController < ApplicationController
  before_action :twitter_client
  before_action :set_post, only: [:follow,:show]
  def show
  end
  def follow
    @user = User.find_by(id: @post.user_id)
    @client.follow(@user.uid.to_i)
    redirect_to root_path
  end

  private
  def twitter_client
    @client = Twitter::REST::Client.new do |config|
      config.consumer_key = ""
      config.consumer_secret = ""
      config.access_token = ""
      config.access_token_secret =""
    end
  end
  def set_post
    @post = Post.find_by(id: params[:id])
  end
end
routes.rb
get "post/:id/follow" => "post#follow"

結構postのidをshowからfollowに渡すのに手間取った。結論URLにidを入れて受け渡しをした。個人的にはapplication_controller.erbにいれた方が他のところでもtwitterapi使えて便利。ただtwitter_clientを毎度そのメソッドの前に行わないといけないのでbeforeで指定するのを忘れずに。

また

config.access_token = ""
config.access_token_secret =""

はユーザー固有のものになるのでログイン時に取得して保持する必要がある。

2
4
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
4