ruby
1<div class="main posts-index"> 2 <div class="container"> 3 <% @posts.each do |post| %> 4 <%user = @users%> 5 <div class="posts-index-item"> 6 <div class="post-left"> 7 <img src="<%= "/user_images/#{post.user.image_name}" %>"> 8 </div> 9 <div class="post-right"> 10 <div class="post-user-name"> 11 <%= link_to(post.user.name, "/users/#{post.user.id}") %> 12 </div> 13 <%= link_to(post.content, "/posts/#{post.id}") %> 14 </div> 15 <% end %> 16 </div> 17</div> 18
user.rb モデル
ruby
1class User < ApplicationRecord 2 validates :name, {presence: true, uniqueness: true} 3 validates :email, {presence: true, uniqueness: true} 4 validates :password, {presence: true} 5 6 def posts 7 return Post.where(user_id: self.id) 8 end 9 end
post.rb モデル
ruby
1class Post < ApplicationRecord 2 validates :content, {presence: true} 3 validates :user_id, {presence: true} 4 5 def user 6 return User.find_by(id: self.user_id) 7 end 8 end
postテーブル
ruby
1class CreatePosts < ActiveRecord::Migration[5.2] 2 def change 3 create_table :posts do |t| 4 t.text :comment 5 t.text :site 6 t.text :url 7 t.text :content 8 t.text :tag 9 10 t.timestamps 11 end 12 end 13end 14
postテーブル追加項目
ruby
1class AddUserIdToPosts < ActiveRecord::Migration[5.2] 2 def change 3 add_column :posts, :user_id, :integer 4 end 5end
postコントローラー
ruby
1class PostsController < ApplicationController 2 before_action :authenticate_user 3 def index 4 @posts = Post.all.order(created_at: :desc) 5 end 6 def show 7 @post = Post.find_by(id: params[:id]) 8 @user = @post.user 9 @likes_count = Like.where(post_id: @post.id).count 10 end 11 12 def new 13 end 14 15 def create 16 @post = Post.new(posts_params) 17 18 if @post.save 19 flash[:notice] = "投稿完了" 20 redirect_to("/posts/index") 21 else 22 render("/posts/new") 23 end 24 25 end 26 27 def posts_params 28 #投稿内容をパラメータで受け取る 29 params.permit(:comment, :site, :url, :content, :tag).merge(user_id: @current_user.id) 30 end 31 32 33 def edit 34 @post = Post.find_by(id: params[:id]) 35 end 36 37 def destroy 38 @post = Post.find_by(id: params[:id]) 39 @post.destroy 40 redirect_to("/posts/index") 41 end 42end 43
現在post.user.image_nameの部分のimage_nameの部分が未定義というエラーが起きています。
他のファイルでは@users.image_nameのような使い方で利用できています。
オブジェクト.オブジェクト?.メソッドのような形の仕組みをイマイチ理解できていません。
解決法と仕組みについてご教授願います。
回答2件
あなたの回答
tips
プレビュー