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

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

メモ(Rails IX)

モデル内でインスタンスメソッドを使ったfind_byの書き換え

ムズいわ、はっきり言って。また出たよ、俺の苦手な「self」・・・。

#posts_controller.rb

def show
    @post = Post.find_by(id: params[:id])
    @user = User.find_by(id: @post.user_id)
  end

#post.rb

def user
    return User.find_by(id: self.user_id)
  end
#posts_controller.rb

def show
    @post = Post.find_by(id: params[:id])
    @user = @post.user
  end

インスタンスメソッドを使って引っ張る

上記の応用。便利な気がするぞ

#index.html.erb

<div class="main posts-index">
  <div class="container">
    <% @posts.each do |post| %>
      <div class="posts-index-item">
        <div class="post-left">
          <img src="<%= "/user_images/#{post.user.image_name}" %>">
        </div>
        <div class="post-right">
          <div class="post-user-name">
            <%= link_to(post.user.name, "/users/#{post.user.id}") %>
          </div>
          <%= link_to(post.content, "/posts/#{post.id}") %>
        </div>
      </div>
    <% end %>
  </div>
</div>

where

  • ある条件に合致する「複数の」データを取得するには、whereメソッドを用いる
  • やべえ頭がぐるぐる回り出した
  • これがこう行って、こっちに行って、の組み合わせで出来てるのね
  • 柔軟な脳味噌が求められる感じ
  • もはやフーン感皆無
  • 何回も見返そうと思う
#user.rb

def posts
    return Post.where(user_id: self.id)
  end
#post.rb

def user
    return User.find_by(id: self.user_id)
  end
#posts_controller.rb

def show
    @post = Post.find_by(id: params[:id])
    @user = @post.user
  end
#show.html.erb

<% @user.posts.each do |post| %>

      <div class="posts-index-item">
        <div class="post-left">
          <img src="<%= "/user_images/#{post.user.image_name}" %>">
        </div>
        <div class="post-right">
          <div class="post-user-name">
            <%= link_to(post.user.name, "/users/#{post.user.id}") %>
          </div>
          <%= link_to(post.content, "/posts/#{post.id}") %>
        </div>
      </div>

    <% end %>

投稿者以外はリダイレクト

注意点として、これはビフォーアクションなので、showアクションと同様、最初に@postを定義する必要がある

#posts_controller.rb

before_action :ensure_correct_user, {only: [:edit, :update]}
#中略
def ensure_correct_user
    @post = Post.find_by(id: params[:id])

    if @current_user.id != @post.user_id
      flash[:notice] = "権限がありません"
      redirect_to("/posts/index")
    end

  end