我正在努力使用我的 rails 应用程序,因为我试图在他们的个人资料页面上添加来自用户的帖子。我正在使用设备,并且已经在网上寻找解决方案,但似乎都没有工作。
我正在运行 Rails 服务器 5.2。
这是我的一些代码:
#app/models/user.rb
class User < ActiveRecord::Base
has_many :posts
end
#app/models/post.rb
class Post < ActiveRecord::Base
belongs_to :user
end
这是 users.controller.rb
class UsersController < ApplicationController
def show
@user = User.find(params[:id])
@posts = current_user.posts
end
end
和我的posts_controller.rb
:
class PostsController < ApplicationController
before_action :set_post, only: [:show, :edit, :update, :destroy]
before_action :authenticate_user!, except: [:show, :index]
# GET /posts
# GET /posts.json
def index
@posts = Post.all
end
这是 users/show.html.erb
<%= @user.about %>
<% @posts.each do |post| %>
<%= post.title %>
<% end %>
它似乎不起作用,因为我遇到了这个特定的错误:nil:NilClass 的未定义方法 `each'
<%= @user.about %>
<% @posts.each do |post| %>
<%= post.title %>
<% end %>
既然你找到了解决方案,这里是建议。
class UsersController < ApplicationController
def show
@user = User.find(params[:id])
@posts = current_user.posts
end
end
将其更改为
class UsersController < ApplicationController
before_action :authenticate_user!
def show
@user = current_user
@posts = current_user.posts
end
end
before_action :authenticate_user!
是为了获取当前用户,在大多数情况下用户需要登录才能查看/编辑他们的个人资料,因此我们应该要求用户登录@user = current_user
因为现在登录的用户是我们需要显示或编辑的用户对象本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句