0
0

More than 1 year has passed since last update.

共同開発 ルーティング nemespace

Posted at

自分のメモ用程度に作成してます。

:shamrock:namespaseを使用して顧客と管理者のルーティング作成

:star:管理者用

routes.rb
      devise_for :admin, skip: [:registrations, :passwords], controllers: {
      sessions: "admin/sessions"
    }
      namespace :admin do
        get '/' => 'homes#top'
        resources :items, except: [:destroy]
        resources :genres, only: [:index, :create, :edit, :update]
        resources :customers, only: [:index, :show, :edit, :update]
        resources :orders, only: [:show, :update]
        resources :order_details, only: [:update]
      end

:snowflake:namespace :admin doを指定することで管理者と顧客に分けてcontrollerやviewsを作成できる。
URLにadminが含まれる。
パス:/admin/items
コントローラー:Admin::itemsController
のようになる。
:star:顧客用

routes.rb
      devise_for :customers, skip: [:passwords], controllers: {
      registrations: "public/registrations",
      sessions: 'public/sessions'
    }
   
    scope module: :public do
    root :to =>"homes#top" 
    get '/about' => 'homes#about'
    resources :items, only: [:index, :show]
    resources :customers, only: [:show, :edit, :update] do
      collection do
        get 'check_out'
        patch 'withdraw'
      end
    end
     resources :cart_items, only: [:index, :update, :destroy] do
      collection do
        delete 'all_destroy'
      end
    end
     resources :orders, only: [:new, :create, :index, :show] do
      collection do
        get 'confirm'
        get 'complete'
      end
    end
     resources :addresses, except: [:new, :show]
  end
end

:snowflake:scope module: :publicという記述は、Railsのルーティングで、「この範囲のルーティングはpublicフォルダ内のコントローラを使う」と指示するためのものです。これにより、コントローラの配置場所とコードの整理がしやすくなります。ただし、この設定はnamespace :admin doのようにURLに/publicが含まれるわけではありません。

:snowflake:collection doはRailsのルーティングにおいて、特定のリソース全体に対して動作するカスタムアクションを定義するためのブロックです。具体的には、特定のIDを必要としないアクションを追加するのに使います。例えば、check_outやwithdrawのようなアクションです。


routes.rb
#管理者側ルーティング
      devise_for :admin, skip: [:registrations, :passwords], controllers: {
      sessions: "admin/sessions"
    }
#顧客側ルーティング
      devise_for :customers, skip: [:passwords], controllers: {
      registrations: "public/registrations",
      sessions: 'public/sessions'
    }

:snowflake:ここではdevise_forメソッドを使用して、adminとcustomersという2つの異なるユーザーグループ(管理者と顧客)に対する認証機能を作成しています。devise_forはDeviseというRailsの認証システムを利用するためのメソッドです。

:snowflake:skip: [:registrations, :passwords] の部分では、特定の認証関連のルート(パスワード変更や登録など)をスキップ(除外)しています。例えば、skip: [:registrations, :passwords]を指定すると、新規登録やパスワード変更のルートは作成されません。

管理者用:管理者がログイン・ログアウトできる機能を提供します。新規登録やパスワードの変更はスキップします。
顧客用:顧客が新規登録、ログイン、ログアウトを行う機能を提供します。パスワードの変更はスキップします。


参考

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