Why not login to Qiita and try out its useful features?

We'll deliver articles that match you.

You can read useful information later.

3
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

【rails】twitter認証からアイコン画像を取得する

Last updated at Posted at 2019-11-03

##はじめに
アイコン画像を表示するのに苦労したのでメモを残します。

##開発環境
Ruby on Rails 5.2

##手順

###取得方法

以下の様に記入して、twitter認証時にアイコン画像を取得します。

user.rb
def self.find_or_create_from_auth(auth)
    provider = auth[:provider]
    uid = auth[:uid]
    name = auth[:info][:name]
    image = auth[:info][:image]#これがアイコン画像
    introduction = auth[:info][:description]

    find_or_create_by(provider: provider, uid: uid) do |user|
      user.name = name
      user.image_url = image  #image_urlにアイコンのURLが入る
      user.introduction = introduction
    end
  end

###表示方法

ビューにログインユーザー画像を表示させます。
twitterユーザーとそれ以外のユーザーで区別します。

index.html.erb
  <% if user.uid != nil %>
    <img src="<%= user[:image_url] %>" >
  <% else %>
    <%= image_tag user.image.to_s %>
  <% end %>

これでアイコン画像を表示できました!

##最後に
uidがあるかないかでifの条件を作りましたが
他にもいい方法があるかもしれません。

3
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

Qiita Advent Calendar is held!

Qiita Advent Calendar is an article posting event where you post articles by filling a calendar 🎅

Some calendars come with gifts and some gifts are drawn from all calendars 👀

Please tie the article to your calendar and let's enjoy Christmas together!

3
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?