LoginSignup
0
0

More than 1 year has passed since last update.

railsチュートリアル第十四章 [Follow]ボタン(基本編)

Posted at

[Follow]ボタン(基本編)

Follow]/[Unfollow]ボタンを動作させましょう
そのために
Relationshipsコントローラが必要です。いつものようにコントローラを生成しましょう。

ubuntu:~/environment/sample_app (following-users) $ rails generate controller Relationships
Running via Spring preloader in process 4782
      create  app/controllers/relationships_controller.rb
# コントローラ
      invoke  erb
      create    app/views/relationships
      invoke  test_unit
      create    test/controllers/relationships_controller_test.rb
# テスト
      invoke  helper
      create    app/helpers/relationships_helper.rb
# ヘルパー
      invoke    test_unit
      invoke  assets
      invoke    scss
      create      app/assets/stylesheets/relationships.scss
# scss

リレーションシップの基本的なアクセス制御に対するテスト

test/controllers/relationships_controller_test.rb

require 'test_helper'

class RelationshipsControllerTest < ActionDispatch::IntegrationTest

  test "create should require logged-in user" do
    assert_no_difference 'Relationship.count' do
    # Relationshipのカウントが変わっていないことを確認
      post relationships_path
    end
    assert_redirected_to login_url
  end

  test "destroy should require logged-in user" do
    assert_no_difference 'Relationship.count' do
      delete relationship_path(relationships(:one))
    end
    assert_redirected_to login_url
    # もしログインしていなければログインページにリダイレクトされる
  end
end

リレーションシップのアクセス制御

app/controllers/relationships_controller.rb

class RelationshipsController < ApplicationController
  before_action :logged_in_user
  # ログインされていることが前提
  def create
  end

  def destroy
  end
end

Relationshipsコントローラ

app/controllers/relationships_controller.rb

class RelationshipsController < ApplicationController
  before_action :logged_in_user
  # ログインされていることが前提
  def create
    user = User.find(params[:followed_id])
    current_user.follow(user)
    redirect_to user
  end

  def destroy
    user = Relationship.find(params[:id]).followed
    current_user.unfollow(user)
    redirect_to user
  end
end

演習

1.
ブラウザ上から /users/2 を開き、[Follow]と[Unfollow]を実行してみましょう。うまく機能しているでしょうか?

確認
2.
先ほどの演習を終えたら、Railsサーバーのログを見てみましょう。フォロー/フォロー解除が実行されると、それぞれどのテンプレートが描画されているでしょうか?

users/show.html.erb

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