我正在創建一個博客應用程序,當用戶查看帖子索引視圖時,我希望他們只編輯和刪除他們創建的帖子。我收到以下錯誤: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
如果你遵循約定,你很可能在索引操作中沒有'@ post'實例變量。你有'@ posts',然後你用'each'循環它,即'@posts.each do | post |'。因此,在索引視圖中將'@ post'更改爲'post'並查看是否有效。 – jvnill