1
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.

複数モデルを使うdeviseのauthenticateについて

Last updated at Posted at 2021-03-10

WHY

オリアプで複数のモデルを作成したときコントローラーのbefore_action :authenticateですこし詰まったとこがあるので


やりたいこと

コントローラー内

class ShopItemsController < ApplicationController
  before_action :authenticate_user!,only: [:search]
  before_action :authenticate_shop!,only: [:new,:create]

  def search
  end

  def new
    @shop_item = ShopItem.new
  end

  def create
    @shop_item = ShopItem.create(shop_item_params)
  end

  def show
    @shop_items = SearchItemService.make_items(@shop.shop_items)
  end

# 〜省略〜

deviseで「shop」と「user」という二つのモデルを作成した。
ShopItemsコントローラーを作成し、これらのアクションのうち、showアクションに至っては、「user、もしくはshopどちらかがログインしていれば行える」といった処理にしたい

問題

仮に

  before_action :authenticate_user!,only: [:show]
  before_action :authenticate_shop!,only: [:show]

とした場合、userのログイン状態のときは「:authenticate_shop!」が、
shopログイン時は「:authenticate_user!」が起きてしまう。

「:authenticate_user_shop!」と言う書き方ができるという記事を見つけたが、自分の場合はどうもエラーがおきてしまう。

解決

自分でauthenticateメソッドを作る
やりたいことをもう一度確認してみると、
「user、もしくはshopどちらかがログインしていれば行える」

どうやらif文を使えばいけそうな気がする。
ということでアプリケーションコントローラーにメソッドを定義していく。

application_controller

def authenticate_any!
  if shop_signed_in?
      true
  else
      authenticate_user!
  end
end

解説

if shop_signed_in?
      true

showアクションを行う際にまずはshopがログインしているかを行う
ログインしていればshowアクションを使うことができるためtrueを返す。

else
   authenticate_user!
end

shopでログインしていなかった場合、「authenticate_user!」を行う。
これでuserでもログインしていなければログインページへ遷移させることができる。

最後にShopItemsコントローラーに記述する

before_action :authenticate_any!,only: [:show]

二つのモデルを作成する場合いろいろな問題出てきてしまいますが、今となってはいろんなことを知ることができるのでよかったとおもってます。今回参考にした記事です
https://laptrinhx.com/rails-devise-fu-shumoderuwo-guan-lisuru-jino-before-action-25820567/

1
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
1
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?