我有想要在产品视图中发布的用户信息。我该怎么做呢?
undefined method 'avatar' for nil:NilClass
<%= image_tag(@user.avatar.url(:thumb)) %>
<%= link_to @post.user.name, @post.user %>
我有帖子,产品,用户模型和控制器
PostsController.rb
class PostsController < ApplicationController
before_action :find_post, only: [:show, :edit, :update, :destroy]
before_action :authenticate_user!, except: [:index, :show]
def index
if
params[:category].blank?
@posts = Post.all.order("created_at DESC").paginate(page:params[:page], per_page: 6 )
else
@category_id = Category.all
@category_id = Category.find_by(name: params[:category]).id
@posts = Post.where(category_id: @category_id).order("created_at DESC").paginate(page:params[:page], per_page: 6 )
end
end
def show
@user = User.find_by id: @post.user_id
end
def new
@post = current_user.posts.build
end
def create
@post = current_user.posts.build(post_params)
if @post.save
redirect_to @post
else
render 'new'
end
end
def update
if @post.update(post_params)
redirect_to @post
else
render 'edit'
end
end
def edit
end
def destroy
@post.destroy
redirect_to root_path, notice: "The post was deleted"
end
private
def find_post
@post = Post.find(params[:id])
end
def post_params
params.require(:post).permit(:title)
end
end
UsersController.rb
class UsersController < ApplicationController
before_action :authenticate_user!
before_action :set_user
def index
@users = User.all
end
def edit
@user = User.create( user_params )
end
def show
@user = User.friendly.find(params[:id])
@product = current_user.products.where(availability: true).order("created_at DESC")
@purchased = Sale.where(buyer_email: current_user.email).order("created_at DESC")
@sales = Sale.where(seller_email: current_user.email).order("created_at DESC")
@products = current_user.products
end
def profile
@products = current_user.products
end
private
def user_params
params.require(:user).permit(:name, :email, :avatar, :id)
end
def set_user
@user = User.friendly.find(params[:id])
end
end
任何帮助将不胜感激。我基本上想创建一个链接,但是存在一个问题,因为我不确定如何连接这些控制器和模型。
答案 0 :(得分:1)
看来,你正在渲染posts/new.html.erb
。但您尚未向:new
过滤器添加before_action
操作。这就是@user
为nil
的原因。添加它:
class PostsController < ApplicationController
before_action :find_post, only: [:show, :edit, :update, :destroy, :new ]
答案 1 :(得分:0)
undefined method 'avatar' for nil:NilClass
表示加载页面时@user
为零,因此页面加载在此行失败:<%= image_tag(@user.avatar.url(:thumb)) %>
id
参数为空,或者它以某种方式无效(例如,没有具有该ID的用户),@user = User.friendly.find(params[:id])
不是{\ n}}找到任何东西。
User.friendly.find
,@user
中调用的库似乎未被正确配置以解析该调用。在此期间,您可以使用在帖子控制器中使用的相同方法来填充@user = User.find_by id: @post.user_id
:{{1}}