LoginSignup
3
0

More than 3 years have passed since last update.

【Rails6】簡単ログイン・ゲストログイン機能のuser情報にActive Storageを用いている場合

Posted at

はじめに

簡単ログイン機能は以下の記事を参考にして、実装しました。
かなりわかりやすい記事なので、簡単ログインを実装する際にはぜひご参考ください。

本記事は上の記事の追加情報となります。

user情報にActive Storageを用いて、画像登録の設定をしているという記事を見たことがなかったので、作成してみました。

バージョン

rubyのバージョン ruby-2.6.5
Railsのバージョン Rails:6.0.0

概要

上記の記事に加えて、新規登録情報にActive Storageを用いて画像の登録を行っている場合に、実装に必要な記述についてご紹介します。

image.png

結論

コントローラー内に以下のimage.attachの記述を行う。

app/controllers/homes_controller.rb

# 〜省略〜

def new_guest
    user = User.find_or_create_by!(nickname:'guest', email: 'guest@example.com', occupation: 'guest', position: 'guest', birth_day: '1990-10-10', sex_id: 2) do |user|
      user.password = SecureRandom.urlsafe_base64
      user.image.attach(io: File.open(Rails.root.join("app/assets/images/homekatajiten.png")), filename: "homekatajiten.png") # ←こちらです!
    end
    sign_in user
    redirect_to root_path, notice: 'ゲストユーザーとしてログインしました。'
  end

# 〜省略〜

補足説明

Active Storageでimageカラムを取り込んでいるので、usersテーブルにimageカラムをattachします。

imageカラムをfind_or_create_byメソッドの引数に含めるとエラーが起こります。
というのもuserテーブルにimageカラムがないからです。

以上です。

3
0
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
3
0