学生向けプログラミング入門 | 無料

学生向けにプログラミングを無料で解説。Java、C++、Ruby、PHP、データベース、Ruby on Rails, Python, Django

Rails7.1 | 動画学習アプリ作成 | 23 | コントローラー

↓↓クリックして頂けると励みになります。



22 | アクションテキスト(ActionText)】 << 【ホーム】 >> 【24 | プロジェクトの登録


部屋コントローラー作成
コントローラー作成


Ruby on Railsのコントローラー(Controller)は、MVC(Model-View-Controller)アーキテクチャの一部です。
コントローラーは、アプリケーションを管理し、クライアントからのリクエストを受け取り、それに応じてモデルとビューとの間で情報を調整します。
Ruby on Railsのコントローラーは一般的にアプリケーション内でルーティングと結びつき、HTTPリクエストに応じて特定のコントローラーアクションが呼び出されます。
アクションはRubyメソッドとして実装され、特定のビューをレンダリングしたり、リダイレクトしたり、データを操作したりする役割を果たします。
コントローラーはユーザーインターフェースとデータモデルを結びつける役割を果たします。


では早速、ジェネレーターを利用してコントローラー作成してみます。

プロジェクトコントローラー

プロジェクトコントローラを作成します。


コマンド
rails g controller Projects index new show create naming pricing description photo_upload update


app\controllers\projects_controller.rb

class ProjectsController < ApplicationController
 
  before_action :authenticate_user!, except: [:show]
  before_action :set_project, except: [:new, :create, :show, :index]

  def index
  	@projects = Project.all
  end

  def new
    @project = current_user.projects.build
  end

  def create
    @project = current_user.projects.build(project_params)
    if @project.save
      redirect_to naming_project_path(@project), notice: "保存しました"
    else
      redirect_to request.referrer, flash: { error: @project.errors.full_messages }
    end
  end

  def update
    new_params = project_params
    if @project.update(new_params)
      flash[:notice] = "保存しました。"
    else
      flash[:alert] = "問題が発生しました。"
    end
    redirect_back(fallback_location: request.referer)
  end

  def show
  	@project = Project.find(params[:id])
  	@tasks = @project.tasks.order(:tag)
        @i = 0
        @images = @project.images
  end

  def edit
        @project = Project.find(params[:id])
  	@tasks = @project.tasks.order(:tag)
  end

  def upload_photo
  end

  def delete_photo
  end

  private
  def set_project
    @project = Project.find(params[:id])
  end

  def project_params
    params.require(:project).permit(:name, :content, :price, :description, :images, :active)
  end
end



タスクコントローラー



タスクコントローラを作成します。


コマンド
rails g controller Tasks index new show create naming description update


app\controllers\tasks_controller.rb

class TasksController < ApplicationController

  before_action :set_task, except: [:index, :new, :create, :show]
  before_action :authenticate_user!, except: [:show]

  def index
         project = Project.find(params[:project_id])
  	@tasks = project.tasks.order(:tag)
  end

  def new
    @task = Task.new
    @projects = Project.all
  end

  def show
         project = Project.find(params[:project_id])
  	@tasks = project.tasks.order(:tag)
        @task = Task.find(params[:id])
  end

  def create
    @task = Task.new(task_params)
    if @task.save
      redirect_to naming_task_path(@task), notice: "保存しました。"
    else
      redirect_to request.referrer, flash: { error: @task.errors.full_messages }
    end    

  end

  def naming
  end

  def description
  end

  def video
    @projects = Project.all
  end

  def update
    new_params = task_params
    if @task.update(new_params)
      flash[:notice] = "保存しました。"
    else
      flash[:alert] = "問題が発生しました。"
    end
    redirect_back(fallback_location: request.referer)
  end

  private
  # コールバックを使用して、アクション間で共通のセットアップまたは制約を共有します。
  def set_task
    @task = Task.find(params[:id])
  end

  # 信頼できるパラメータのリストのみを許可します。
  def task_params
    params.require(:task).permit(:title, :note, :video, :header, :description, :tag, :active, :project_id)
  end

end



ルートの設定をします。


自動で書かれた記述は削除します。


記述追加 config\routes.rb(20行目)

  resources :projects do
    member do
      get 'naming'
      get 'pricing'
      get 'description'
      get 'photo_upload'
      delete :delete_photo
      post :upload_photo
    end
    resources :tasks, only: [:show, :index]
  end

  resources :tasks, except: [:edit] do
    member do
      get 'naming'
      get 'description'
      get 'video'
      get 'code'
    end
  end



config\routes.rb

Rails.application.routes.draw do

  # ルートを app\views\pages\home.html.erb に設定
  root 'pages#home'

  # get
  get 'pages/home'
  get '/dashboard', to: 'users#dashboard'
  get '/users/:id', to: 'users#show', as: 'user'

  # post
  post '/users/edit', to: 'users#update'

  # device
  devise_for :users, 
    path: '', 
    path_names: {sign_up: 'register', sign_in: 'login', edit: 'profile', sign_out: 'logout'},
    controllers: {omniauth_callbacks: 'omniauth_callbacks', registrations: 'registrations'}

  resources :projects do
    member do
      get 'naming'
      get 'pricing'
      get 'description'
      get 'photo_upload'
      delete :delete_photo
      post :upload_photo
    end
    resources :tasks, only: [:show, :index]
  end

  resources :tasks, except: [:edit] do
    member do
      get 'naming'
      get 'description'
      get 'video'
      get 'code'
    end
  end

  # Define your application routes per the DSL in https://guides.rubyonrails.org/routing.html

  # Reveal health status on /up that returns 200 if the app boots with no exceptions, otherwise 500.
  # Can be used by load balancers and uptime monitors to verify that the app is live.
  get "up" => "rails/health#show", as: :rails_health_check

  # Defines the root path route ("/")
  # root "posts#index"
end




22 | アクションテキスト(ActionText)】 << 【ホーム】 >> 【24 | プロジェクトの登録





↓↓クリックして頂けると励みになります。