2016-12-14 62 views
0

我正在創建一個博客應用程序,當用戶查看帖子索引視圖時,我希望他們只編輯和刪除他們創建的帖子。我收到以下錯誤:Ruby-On-Rails如何只允許當前用戶編輯和刪除他們創建的帖子

未定義的方法`user_ID的」爲無:NilClass

的意見/職位/ 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 %> 

以上是我的聲明,如果允許用戶只能編輯並刪除他們創建的帖子。

在post_controller創建方法:

def create 
    @post = Post.new(post_params) 
    @post.user = current_user 

    respond_to do |format| 
     if @post.save 
     format.html { redirect_to @post, notice: 'Post was successfully created.' } 
     format.json { render :show, status: :created, location: @post } 
     else 
     format.html { render :new } 
     form 

at.json { render json: @post.errors, status: :unprocessable_entity } 
     end 
    end 
    end 
+0

如果你遵循約定,你很可能在索引操作中沒有'@ post'實例變量。你有'@ posts',然後你用'each'循環它,即'@posts.each do | post |'。因此,在索引視圖中將'@ post'更改爲'post'並查看是否有效。 – jvnill

回答

1

我做了編輯動作過濾器之前,更新的方並銷燬行動:

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和th您在創建新帖子時定義的e @ 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 

在您的文章視圖,您必須添加條件代碼來渲染編輯和刪除鏈接只有在用戶是正確的:

<% 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 %> 
+0

當你說發佈視圖你是指索引視圖嗎? – Jill

+0

我將你的代碼添加到我的帖子索引視圖,然後我得到這個錯誤 未定義的方法'current_user?'對於#<#:0x62c3688> – Jill

+0

您沒有從SessionHelper添加代碼。你是否登錄用戶並設置了current_user? –

1

要確保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 
+0

它仍然說nil:NilClass爲第40行的未定義方法'user_id',即: <%if current_user.id == @ post.user_id%> – Jill

+0

如果您只是執行'<%= current_user,那麼您會得到什麼結果? id%><%= @ post.user_id%>' –

+0

雖然我不需要if statemnet嗎? – Jill

相關問題