LoginSignup
takuyahori
@takuyahori (堀 拓也)

Are you sure you want to delete the question?

If your question is resolved, you may close it.

Leaving a resolved question undeleted may help others!

We hope you find it useful!

deviseで複数モデル管理をしている際のauthenticate_user!メソッドの記述について

解決したいこと

画像投稿アプリを作成しておりまして、ログインしていないユーザーが、URLの直接入力にて投稿編集ページに
飛べないようにauthenticate_user!メソッドを使用したのですが、trainerとcliantの2パターンでユーザー
登録を分けているため、例えばcliantがログインしている場合はauthenticate_trainer!が働いてしまい、
うまくいきません。
deviseで複数モデル管理をしている場合のauthenticate_user!メソッドの記述方法についてご教示
いただきたいです。

該当するソースコード

application.controller
class ApplicationController < ActionController::Base
  before_action :basic_auth
  before_action :authenticate_trainer!, except: [:index, :show]
  before_action :authenticate_cliant!, except: [:index, :show]

  def after_sign_in_path_for(resource)
    posts_path(resource)
  end

  def basic_auth
    authenticate_or_request_with_http_basic do |username, password|
      username == ENV["BASIC_AUTH_USER"] && password == ENV["BASIC_AUTH_PASSWORD"]
    end
  end
end

自分で試したこと

application.controller
class ApplicationController < ActionController::Base
  before_action :basic_auth
  before_action :authenticate_any!

  def authenticate_any!
    if cliant_signed_in?
      true
    else
      authenticate_trainer!
    end
  end

  def after_sign_in_path_for(resource)
    posts_path(resource)
  end

  def basic_auth
    authenticate_or_request_with_http_basic do |username, password|
      username == ENV["BASIC_AUTH_USER"] && password == ENV["BASIC_AUTH_PASSWORD"]
    end
  end
end

上記のように自分でメソッドを作って記述もしてみましたがうまくいかず、、、
アドバイスお願い致します。

0

2Answer

よろしくお願いします。
current_user.idがテーブルにあるかどうかで条件分岐させるのはどうでしょうか。

0Like

Comments

  1. @takuyahori

    Questioner
    アドバイスありがとうございます!
    下記のように記述してみましたがうまくいきません、、、

    before_action :authenticate_any!

    def authenticate_any!
    if current_cliant.id.present
    true
    else
    authenticate_trainer!
    end
    end

    記述的に間違っている部分があればアドバイスいただきたいです、、、

拓也さんの記述とは違いますが、deviseのヘルパーメソッドにあるcurrent_userを使った例だと以下のようになるかと思います。

current_user(deviseのヘルパーで、現在ログインしているuserの情報が取得できる)のidがデータベースにあるかどうかであれば、

if current_user.id == User.find[params[:current_user.id]

みたいな感じで、ログインしているuserのidと、Userモデルの中にログインしているuserのidがあるのかどうかという感じになるかなと思いました。

0Like

Comments

  1. @takuyahori

    Questioner
    アドバイスありがとうございます!
    参考にさせていただきまして記述してみましたが、
    Couldn`t find Post without an IDのエラーが出てしまいました、、、
    deviseの複数モデル機能だとうまくいかないのでしょうか、、、
  2. current_userはdeviseのヘルパーメソッドで、現在ログインしている人のidを表示するのでログインしていないのであればエラーになるかもです!
    上手く伝えることができずすいません。。
  3. @takuyahori

    Questioner
    返信遅くなってしまいすみません、、、
    おっしゃる通り、ログインしていないとエラーになるようでした。

    def redirect_root
    redirect_to root_path unless cliant_signed_in? or trainer_signed_in?
    end

    上記のように記述し、ログインしていない場合はトップページに飛ばす記述にしてみたら
    行けました!

    ご回答ありがとうございました!
  4. ログインしていない人がログインした場合の処理の分岐を書いていた方がいいかなとは思っていました!
    無事解決したのならよかったです!
    これからも頑張りましょう!

Your answer might help someone💌