「app\controllers」フォルダに「reviews_controller.rb」ファイルを新規作成してください。
app\controllers\reviews_controller.rb(新規作成したファイル)
class ReviewsController < ApplicationController def create if Review.exists?(project_id: review_params[:project_id], user_id: current_user.id) flash[:alert] = "レビュー済みです。" else @review = Review.create(review_params) project = @review.project if @review.save flash[:notice] = "レビューを投稿しました。" else flash[:alert] = "レビューできません" end end redirect_to request.referrer end def destroy @review = Review.find(params[:id]) project = @review.project @review.destroy flash[:alert] = "レビューを削除しました。" redirect_to project end private def review_params params.require(:review).permit(:stars, :review, :project_id, :user_id) end end
「app\controllers\project_controller.rb」ファイルに以下の記述を追加します。
記述追加 app\controllers\project_controller.rb(18行目)
@review = Review.new @reviews = @project.reviews.order('created_at desc') @hasReview = @reviews.find_by(user_id: current_user.id) if current_user
app\controllers\project_controller.rb
class ProjectController < ApplicationController before_action :set_project, only: [:show] before_action :authenticate_user!, only: [:list] def index @projects = Project.all end def show @tasks = @project.tasks.order(:tag) @joined = false if !current_user.nil? && !current_user.projects.nil? @joined = current_user.projects.include?(@project) end @users = @project.users.order('created_at desc').first(10) @review = Review.new @reviews = @project.reviews.order('created_at desc') @hasReview = @reviews.find_by(user_id: current_user.id) if current_user end def list if !current_user.nil? @projects = current_user.projects end end private # コールバックを使用して、アクション間で共通のセットアップまたは制約を共有します。 def set_project @project = Project.find(params[:id]) end # 信頼できるパラメータのリストのみを許可します。 def project_params params.require(:project).permit(:name, :content, :price, :active, :description) end end
ルートの設定をします。
1.20行目に以下の記述を追加します。
post '/reviews', to: 'reviews#create'
2.24行目に以下の記述を追加します。
resources :reviews, only: [:create, :destroy]
記述追加 config\routes.rb
Rails.application.routes.draw do # ルートを app\views\pages\home.html.erb に設定 root 'pages#home' devise_for :users, path: '', path_names: {sign_up: 'register', sign_in: 'login', edit: 'profile', sign_out: 'logout'}, controllers: {omniauth_callbacks: 'omniauth_callbacks', registrations: 'registrations'} get 'pages/home' get '/dashboard', to: 'users#dashboard' get '/users/:id', to: 'users#show', as: 'users' get '/myprojects' => 'project#list' get 'settings/payment', to: 'users#payment', as: 'settings_payment' post '/users/edit', to: 'users#update' post '/free' => 'charge#free' post '/settings/payment', to: 'users#update_payment', as: "update_payment" post '/reviews', to: 'reviews#create' resources :project do resources :task, only: [:show] resources :reviews, only: [:create, :destroy] end # For details on the DSL available within this file, see https://guides.rubyonrails.org/routing.html end