LoginSignup
0
0

More than 1 year has passed since last update.

rails5 progate 整理 メモ

Posted at

人に見せるために書いていません。あくまで自分を落ち着かせるためです。

ログインしている場合のアクセス制限

ログイン中のユーザーが以下のURLにアクセスした場合には、投稿一覧ページにリダイレクトしてください。
・get /signup
・get /login
・get / (localhost:3000)
・post /users/create
・post /login

どういう条件をつければいいのだろうか?

前の問題のようにすればいいのではないか?

application_controller.rb
def already_user
    if @current_user
      flash[:notice] = "すでにログインしています"
      redirect_to("posts/index")
    end
  end
users_controller.rb
class UsersController < ApplicationController
  before_action :authenticate_user, {only:[:index, :show, :edit, :update]}
  before_action :already_user, {only:[:new, :create, :login, :login_form]}
.
.
.
home_controller.rb
class HomeController < ApplicationController
  before_action :already_user, {only:[:top]}
.
.
.

ide-proxy.prog-8.composts のサーバーの IP アドレスが見つかりませんでした。

検索してみると...
1.DNSサーバーに該当ドメインが登録されていない
2.DNSサーバーがダウンしている
3.自身のネット回線に問題がある
4.ブラウザやキャッシュに問題がある
これらの原因を見てみたがコードと何が関係あるのかわからなくなった。
答えを見てしまった。

application_controller.rb
def already_user
    if @current_user
      flash[:notice] = "すでにログインしています"
      redirect_to("/posts/index")
    end
  end

/がついていなかったからだ。

思ったこと

/とIPアドレスとの関係がわからない。

自分の情報のみ編集できるようにしよう

before_actionで編集できないようにしよう。

users_controller.rb
  before_action :only_edit,         {only: [:edit, :update]}
.
.
.
  def only_edit
    if @current_user =! User.find_by(id: params[:id])
      flash[:notice] = "権限がありません"
      redirect_to("/posts/index")
    end
  end

end
show.html
.
.
.
<%= link_to("編集", "/users/#{@user.id}/edit")%>
.
.
.

これでできるか。
urlで入力すると違うユーザーに編集できてしまう。
もしかして=!違うのかも。
調べてみると
!=だった。

これを治してみると

users_controller.rb
.
.
.
if @current_user != User.find_by(id: params[:id])
.
.
.

urlで表示されなくなった。これで合格か?
成功!

道場コース終了。

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