Ruby on rails RubyonRails如何只允许当前用户编辑和删除他们创建的帖子

Ruby on rails RubyonRails如何只允许当前用户编辑和删除他们创建的帖子,ruby-on-rails,ruby,Ruby On Rails,Ruby,我正在制作一个博客应用程序,当用户查看帖子索引视图时,我希望他们只编辑和删除他们创建的帖子。我得到以下错误: nil:NilClass的未定义方法“user\u id” views/posts/index.html <td><% if current_user.id == @post.user_id %></td> <td><%= link_to 'Edit', edit_post_path(@post) %>&

我正在制作一个博客应用程序,当用户查看帖子索引视图时,我希望他们只编辑和删除他们创建的帖子。我得到以下错误:


nil:NilClass的未定义方法“user\u id”

views/posts/index.html

    <td><% if current_user.id == @post.user_id %></td>
        <td><%= link_to 'Edit', edit_post_path(@post) %></td>
        <td><%= link_to 'Destroy', post, method: :delete, data: { confirm: 'Are you sure?' } %></td>
        <% end %>

您希望确保if语句位于TD标记的外侧

    <% if current_user && current_user.id == @post.user_id %>
      <td></td>
      <td><%= link_to 'Edit', edit_post_path(@post) %></td>
      <td><%= link_to 'Destroy', post, method: :delete, data: { confirm: 'Are you sure?' } %></td>
    <% end %>



 #Post Controller 
  class Post < ApplicationController
    ...
    def show
      @post = Post.find(params[:id])
    end
    ...
  end

#岗位控制员
类Post
我对编辑、更新和销毁操作执行操作前筛选:

before_action :correct_user, only: [:edit, :update, :destroy]

def correct_user
    @post = Post.find_by(id: params[:id])  // find the post
    unless current_user?(@post.user)
      redirect_to user_path(current_user)
    end
  end
current_user?(@post.user)
这将检查当前_用户和创建新帖子时定义的@post.user是否相同

在我的sessionHelper中,我必须找到定义当前用户的方法:

  def current_user?(user)
    user == current_user
  end

  def current_user
    if(user_id = session[:user_id])
      @current_user ||= User.find_by(id: user_id)
    end
  end
在post视图中,只有在用户正确的情况下,才能添加条件代码来呈现“编辑”和“删除”链接:

<% if current_user?(post.user) %>
          <%= link_to "Edit", edit_micropost_path(micropost) %>
          <%= link_to "Delete", micropost, method: :delete, data: { confirm: "Do you want to delete this post ?"}%>
          <% end %>


它仍然为nil显示未定义的方法'user\u id':第40行的NilClass是:如果你只做了
我不需要if statemnet吗?当前用户和post.user\u id必须相同。为nil显示未定义的方法'user\u id':NilClass在它不知道用户id是什么当你说post view时,你是什么意思索引视图?我将您的代码添加到我的帖子索引视图中,然后我得到了一个未定义的错误方法“current_user”,因为您没有从SessionHelper添加代码。您是否登录用户并设置当前用户?是的,索引视图。如果您遵循约定,则索引操作中很可能没有
@post
实例变量。您有
@posts
,然后使用
每个
,即
@posts.each do | post |
循环浏览它。因此,将索引视图中的
@post
更改为
post
,看看是否有效。
<% if current_user?(post.user) %>
          <%= link_to "Edit", edit_micropost_path(micropost) %>
          <%= link_to "Delete", micropost, method: :delete, data: { confirm: "Do you want to delete this post ?"}%>
          <% end %>