##前提・実現したいこと
railsでSNSのようなサイトを作成しておりますが、
投稿一覧画面でユーザー名等を表示したいのですがエラーが発生してしまいます。
rails g migration AddUserIdToPostsでpostsとuserを紐付ける用にマイグレーションファイルをを作成しました。
class AddUserIdToPosts < ActiveRecord::Migration[6.1] def change add_reference :posts, :user, foreign_key: true end end
##エラー内容
NoMethodError in Posts#index Showing /app/app/views/posts/index.html.erb where line #10 raised: undefined method `name' for nil:NilClass Extracted source (around line #10): <div class="name-history"> <div class="name">テキスト 太郎 <%= post.user.name %> </div> <div class="learning-history">学習歴: 2月</div> </div>
##posts_controller.rb
class PostsController < ApplicationController before_action :authenticate_user! before_action :find_post, only: [:show, :edit, :update, :destory] before_action :force_redirect_unless_my_post, only: [:edit, :update, :destory] def index @posts = Post.all.order(created_at: :desc) end def show end def new @post = Post.new end def edit end def create @post = Post.new(post_params) @post.user = current_user if @post.save! redirect_to root_path, notice: '投稿成功!!' else render :new end end def update if @post.update(post_params) redirect_to root_path, notice: '投稿を更新しました。' else render :edit end end def destory if @post.destory redirect_to root_path, notice: '投稿を削除しました。' else redirect_to root_path, alert: '投稿が削除できませんでした。' end end private def post_params params.require(:post).permit( :thumbnail, :title, :version, :code, :description, :video, images: [], ) end def find_post @post = Post.find_by(params[:id]) end def force_redirect_unless_my_post return redirect_to root_path, alert: '自分の投稿ではありません' if @post.user != current_user end end
##models/post.rb
class Post < ApplicationRecord has_many_attached :images has_one_attached :video belongs_to :user end
##models/user.rb
class User < ApplicationRecord devise :database_authenticatable, :registerable, :recoverable, :rememberable, :validatable has_one_attached :image has_many :posts, dependent: :destroy validates :name, presence: true end
##schema.rb
# This file is auto-generated from the current state of the database. Instead # of editing this file, please use the migrations feature of Active Record to # incrementally modify your database, and then regenerate this schema definition. # # This file is the source Rails uses to define your schema when running `bin/rails # db:schema:load`. When creating a new database, `bin/rails db:schema:load` tends to # be faster and is potentially less error prone than running all of your # migrations from scratch. Old migrations may fail to apply correctly if those # migrations use external dependencies or application code. # # It's strongly recommended that you check this file into your version control system. ActiveRecord::Schema.define(version: 2021_02_21_020851) do create_table "active_storage_attachments", charset: "utf8mb4", collation: "utf8mb4_0900_ai_ci", force: :cascade do |t| t.string "name", null: false t.string "record_type", null: false t.bigint "record_id", null: false t.bigint "blob_id", null: false t.datetime "created_at", null: false t.index ["blob_id"], name: "index_active_storage_attachments_on_blob_id" t.index ["record_type", "record_id", "name", "blob_id"], name: "index_active_storage_attachments_uniqueness", unique: true end create_table "active_storage_blobs", charset: "utf8mb4", collation: "utf8mb4_0900_ai_ci", force: :cascade do |t| t.string "key", null: false t.string "filename", null: false t.string "content_type" t.text "metadata" t.string "service_name", null: false t.bigint "byte_size", null: false t.string "checksum", null: false t.datetime "created_at", null: false t.index ["key"], name: "index_active_storage_blobs_on_key", unique: true end create_table "active_storage_variant_records", charset: "utf8mb4", collation: "utf8mb4_0900_ai_ci", force: :cascade do |t| t.bigint "blob_id", null: false t.string "variation_digest", null: false t.index ["blob_id", "variation_digest"], name: "index_active_storage_variant_records_uniqueness", unique: true end create_table "posts", charset: "utf8mb4", collation: "utf8mb4_0900_ai_ci", force: :cascade do |t| t.string "thumbnail" t.string "title" t.integer "version" t.integer "code" t.text "description" t.datetime "created_at", precision: 6, null: false t.datetime "updated_at", precision: 6, null: false t.bigint "user_id" t.index ["user_id"], name: "index_posts_on_user_id" end create_table "users", charset: "utf8mb4", collation: "utf8mb4_0900_ai_ci", force: :cascade do |t| t.string "email", default: "", null: false t.string "encrypted_password", default: "", null: false t.string "reset_password_token" t.datetime "reset_password_sent_at" t.datetime "remember_created_at" t.datetime "created_at", precision: 6, null: false t.datetime "updated_at", precision: 6, null: false t.string "name", default: "", null: false t.text "description" t.index ["email"], name: "index_users_on_email", unique: true t.index ["reset_password_token"], name: "index_users_on_reset_password_token", unique: true end add_foreign_key "active_storage_attachments", "active_storage_blobs", column: "blob_id" add_foreign_key "active_storage_variant_records", "active_storage_blobs", column: "blob_id" add_foreign_key "posts", "users" end
##views/posts/index.html.erb
<div class="wrapper"> <div class="content-block"> <% @posts.each do |post| %> <div class="content"> <div class="user-about"> <div class="image"><%= image_tag 'img1.png' %></div> <div class="profile"> <div class="name-history"> <div class="name">テキスト 太郎 <%= post.user.name %> </div> <div class="learning-history">学習歴: 2月</div> </div> <div class="purpose">Railsを勉強している目的: webエンジニアを目指してRailsを学んで転職活動中!!!</div> </div> </div> <% if post.images.attached? %> <div class="images"> <% post.images.each do |image| %> <%= image_tag image %> <% end %> </div> <% end %> <% if post.video.attached? %> <div class="video"> <%= video_tag(url_for(post.video), style: 'width:100%;height:auto', controls: true, loop: true, autoplay: true, muted: true) %> </div> <% end %> <div class="text"> <%= post.description %> <%= post.thumbnail %> <%= post.title %> <%= post.version %> <%= post.code %> </div> <div class="action-menu"> <div class="like"> </div> <div class="comment"> </div> </div> </div> <% end %> </div> <div class="sidebar"> <div class="box"></div> <div class="box"></div> </div> </div>
回答1件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。