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/