Return to Tech/ruby

Ruby on Rails - Controller and Action


ルーティング調整後

例えば以下のようにゲスト、登録ユーザ、管理者毎に
ページを分けて運用する場合
対応するコントローラとアクションを調整することで実現できます。

http://localhost:3000/guest/
http://localhost:3000/user/
http://localhost:3000/admin/


コントローラの作成 $ bin/rails generate controller guest/t $ bin/rails generate controller user/t $ bin/rails generate controller admin/t 以下生成されたファイルを修正します。 file: webapps/app/controllers/guest/t_controller.rb class Guest::TController < ApplicationController
def idx render action: 'idx' end
end file: webapps/app/controllers/user/t_controller.rb class User::TController < ApplicationController
def idx render action: 'idx' end
end file: webapps/app/controllers/admin/t_controller.rb class Admin::TController < ApplicationController
def idx render action: 'idx' end
end
html(view)の作成 file: webapps/app/views/guest/t/idx.html.erb <% @whoami = 'Guest' %> <%= @whoami %> file: webapps/app/views/user/t/idx.html.erb <% @whoami = 'User' %> <%= @whoami %> file: webapps/app/views/admin/t/idx.html.erb <% @whoami = 'Admin' %> <%= @whoami %>
各URLの表示例

Return to Tech/ruby