LoginSignup
0
0

More than 1 year has passed since last update.

はじめに

本日学んだ事をまとめます。

Deviseを使った認証機能の実装方法とその他のTips

Railsアプリケーションで簡単に認証機能を実装するために、deviseというgemを使ってみましょう。この記事では、deviseのインストール手順から、ログイン後のリダイレクト先やアソシエーション、画像のデフォルト表示などの実装方法について説明します。

Deviseのインストール手順
Gemfileにgem 'devise'を追加
bundle install
rails g devise:install
rails g devise [モデル名]
必要に応じてマイグレーションファイルにt.string :nameを追加
rails db:migrate
rails g devise:views
controllerに追記

ApplicationController.rb
class ApplicationController < ActionController::Base
  before_action :configure_permitted_parameters, if: :devise_controller?

  protected

  def configure_permitted_parameters
    devise_parameter_sanitizer.permit(:sign_up, keys: [:name])
  end
end

認証機能のカスタマイズ

app/controllers/application_controller.rb に追記したconfigure_permitted_parametersメソッドを使って、ユーザー登録時にユーザー名のデータ操作を許可します。
protected は呼び出された他のコントローラからも参照することができます。

フォームのカスタマイズ

<%= f.text_field :name, autofocus: true %> は、HTMLフォーム内にテキストフィールドを作成し、そのフィールドに:nameというシンボルを割り当てます。
<%= f.password_field :password, autocomplete: "current-password" %> は、HTMLフォーム内にパスワードフィールドを作成し、そのフィールドに:passwordというシンボルを割り当てます。

ログイン後の遷移先を設定する

ApplicationController.rb
def after_sign_in_path_for(resource)
  # 遷移したいリンク
end

def after_sign_out_path_for(resource)
  # 遷移したいリンク
end

アソシエーションについて

アソシエーションに関する詳細な説明は、こちらの記事を参照してください。

テーブル名を間違えて作成した場合の対処法

rails generate migration RenameOldTableNameToNewTableName
生成されたマイグレーションファイルを開き、changeメソッドを以下のように修正します。

20230429,,,.rb
def change
  rename_table :old_table_name, :new_table_name
end

注意点: テーブル名は全て小文字のスネークケースで記述する

rails db:migrate

ActiveStorageにデフォルト画像を格納する

画像のサイズ変更をRailsで行います。以下のコードで、no_image.jpgをデフォルト画像としてActiveStorageに格納し、格納した画像を表示します。

Model.rb
class PostImage < ApplicationRecord
  # ...
  def get_image
    unless image.attached?
      file_path = Rails.root.join('app/assets/images/no_image.jpg')
      image.attach(io: File.open(file_path), filename: 'default-image.jpg', content_type: 'image/jpeg')
    end
    image
  end
end

日付データを文字列に変換する

strftime('%Y/%m/%d')メソッドを使うと、日付データを「年/月/日」形式の文字列に変換できます。

プロフィール画像の設定

モデルに以下のコードを追加します。

Model.rb
has_one_attached :profile_image

def get_profile_image(width, height)
  unless profile_image.attached?
    file_path = Rails.root.join('app/assets/images/sample-author1.jpg')
    profile_image.attach(io: File.open(file_path), filename: 'default-image.jpg', content_type: 'image/jpeg')
  end
  profile_image.variant(resize_to_limit: [width, height]).processed
end

has_one_attached :profile_imageで、profile_imageという名前でActiveStorageでプロフィール画像を保存できるように設定します。

これで、deviseを使ってRailsアプリケーションに認証機能を実装し、さまざまなカスタマイズを行う方法がわかりました。

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