8
9

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Ruby on Rails でレビュー機能を実装する

Last updated at Posted at 2019-07-21

Railsでレビュー機能を実装する方法をまとめておきます。

対象者

  • 初心者
  • MVCは理解している

手順

  1. scaffoldで雛形作成
  2. レビュー投稿機能実装
  3. レビュー表示

1. scaffoldで雛形作成

$ rails new review-sample
$ cd review-sample
$ rails g scaffold shop name
$ rails db:migrate

2. レビュー投稿機能実装

2-1. データベース作成

$ rails g model review shop:references body:text
$ rails db:migrate

2-2. shopsコントローラ実装

app/controllers/shops_controller.rb
def show
  @review = Review.new  #追記
end

2-3. ビュー実装

app/views/shops/show.html.erb
<%= form_for @review do |f| %>
  <%= f.hidden_field :shop_id, value: @shop.id %>
  <%= f.text_field :body, class: "text-field" %>
  <%= f.submit '投稿', class: "submit-btn" %>
<% end %>

2-4. reviewsコントローラ実装

2-4-1. reviewsコントローラ作成

$ rails g controller reviews

2-4-2. コントローラ実装

app/controllers/reviews_controller.rb
class ReviewsController < ApplicationController
  def create
    @review = Review.new(review_params)
    @review.save
    redirect_to shop_path(@review.shop)
  end

  private
    def review_params
      params.require(:review).permit(:shop_id, :body)
    end
end

2-5. ルーティング

config/routes.rb
Rails.application.routes.draw do
  resources :shops
  resources :reviews  #追記
end

3. レビュー表示機能

3-1. アソシエーション実装

app/models/shop.rb
class Shop < ApplicationRecord
    has_many :reviews
end

3-2. コントローラ実装

app/controllers/shops_controller.rb
def show
  @review = Review.new
  @reviews = @shop.reviews  # 追記
end

3-3. ビュー実装

app/views/shops/show.html.erb
<% @reviews.each do |r| %>
  <%= r.body %>
<% end %>

動作確認

$ rails s

http://localhost:3000/shops
にアクセス

8
9
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
8
9

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?