LoginSignup
0
1

More than 3 years have passed since last update.

rails 発展その3-2 マイページの作成

Last updated at Posted at 2019-11-08

マイページの作成

基本は:idの使用くらいで他と変わらず
userコントローラーの作成とshowアクションでビューを作成するくらいです。

routes
  Rails.application.routes.draw do
    get     '/コントローラ名/:id'        => 'コントローラ名#show'
  end

# :idの部分には表示するユーザーページのユーザーのidが入ります。

# 例
  Rails.application.routes.draw do
    get   'users/:id'   =>  'users#show'    
  end
  # mypageのルーティング
ターミナル
   $ rails g controller users
app/users/users_controller.rb
# ここも基本欲しいデータ(名前と持っているアイテム一覧)を引っ張ってくる仕様です。
# 又 current_user.カラム名 とすることでログインしてるユーザーのデータを引っ張ってきます。
class UsersController < ApplicationController
    def show
      @name = current_user.name
      @items = item.where(user_id: current_user.id).page(params[:page]).per(5).order("created_at DESC")
    end
  end
app/views/users/show.html.erb
<!-- これでユーザーの名前とアイテムの一覧ができました。 -->
<div class="contents row" >
    <p><%= @name %>さんのアイテム一覧</p>
    <% @items.each do |item| %>
      <div class="content_post" style="background-image: url(<%= item.image %>);">
        <%= simple_format(item.text) %>
        <span class="name"><%= item.name %></span>
      </div>
    <% end %>
    <%= paginate(@tweets) %>
  </div>

ついでにマイページへのリンクがこちら

マイページのリンク
   <a href="/users/<%= current_user.id %>">マイページ</a>
0
1
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
1