BNBのプログラミング勉強記録

ガチのプログラミング初心者が駆け上がっていくブログ

メモ(Rails道場 III)

画像受け取り

binwriteをbinwiteは痛い。エラーメッセージをよく読もう

#没
if params[:image]
      image=params[:image]
      @user.image_name="#{@user.id}.jpg"
      File.binwite("/public/user_images/#{@user.image_name}",image.read)
    end
#正解
if params[:image]
      image=params[:image]
      @user.image_name="#{@user.id}.jpg"
      File.binwrite("public/user_images/#{@user.image_name}",image.read)
    end

現在ログインしているユーザーのidを表示する

  • ヘッダはapplication.html.erbにあるので、@userが使えない
  • 使えるようにするにはapplicationコントローラで設定する必要がある
  • なのでセッションIDを素直に使えばいい
  • liタグごと囲みましょう
#没
<li>
          <% if @user.id==session[:user_id] %>
          現在ログインしているユーザーのid: 
          <%= @user.id %>
          <% end %>
        </li>
#正解
<% if session[:user_id] %>
          <li>
            現在ログインしているユーザーのid:
            <%= session[:user_id] %>
          </li>
        <% end %>

安定の{method:"post"}忘れ

#没
<%= link_to("ログアウト", "/logout") %>
#正解
<%= link_to("ログアウト", "/logout",{method:"post"}) %>

安定の「==」し忘れ

#没
def authenticate_user
    if @current_user=nil
      flash[:notice] = "ログインが必要です"
      redirect_to("/login")
    end
  end
#正解
def authenticate_user
    if @current_user==nil
      flash[:notice] = "ログインが必要です"
      redirect_to("/login")
    end
  end

セッションIDと今見てるユーザー編集ページのIDが合ってるか

  • なんで@userが使えんのや、と一瞬考えたがすぐ分かった
  • これ、before_actionのメソッドなので、@user=User.find_by〜の処理より先にある。すなわち@userが存在せんから、そりゃ使えんわ
#没
def ensure_correct_user
    if session[:user_id]!=@user.id.to_i
      flash[:notice] = "権限がありません"
      redirect_to("/posts/index")
    end
  end
#正解
def ensure_correct_user
    if @current_user.id!=params[:id].to_i
      flash[:notice] = "権限がありません"
      redirect_to("/posts/index")
    end
  end

禁止措置

  • 「あんたそのユーザーじゃないでしょ!」のメソッドを適用するアクションに、updateも加えないと。
  • 多分、これを追加しないと色々悪さできるんじゃないか。
#没
before_action :ensure_correct_user, {only:[:edit]}
#正解
before_action :ensure_correct_user, {only:[:edit,:update]}