[英]How to show some posts options, only for the creator of the post in Rails
我收到错误“ user' for nil:NilClass", but my code looks good to me. I checked from the Rails console, and the posts do have the
未定义方法user' for nil:NilClass", but my code looks good to me. I checked from the Rails console, and the posts do have the
user' for nil:NilClass", but my code looks good to me. I checked from the Rails console, and the posts do have the
user_id`字段,并且按预期工作。
这是我的帖子模型:
# == Schema Information
#
# Table name: posts
#
# id :integer not null, primary key
# body :string
# created_at :datetime not null
# updated_at :datetime not null
# user_id :integer
#
class Post < ActiveRecord::Base
validates :body, presence: true
belongs_to :user
end
这是我的posts控制器中的create
动作:
def create
@post = Post.new(post_params)
@post.user = current_user
if @post.save
redirect_to root_path
else
render :new
end
end
这是我尝试“审核”有权访问编辑和删除权限的部分:
<% if signed_in? && @post.user == current_user %>
<%= link_to "Edit", edit_post_path(post) %>
<%= link_to "Delete", post, method: :delete, data: {confirm: "Are you sure you want to delete this post?"} %>
<%end%>
这是错误跟踪:
Started GET "/" for ::1 at 2016-02-06 15:48:00 -0500
Processing by PostsController#index as HTML
Post Load (0.3ms) SELECT "posts".* FROM "posts" ORDER BY "posts"."id" DESC
User Load (0.1ms) SELECT "users".* FROM "users" WHERE "users"."id" = ? LIMIT 1 [["id", 1]]
Rendered posts/index.html.erb within layouts/application (9.2ms)
Completed 500 Internal Server Error in 46ms (ActiveRecord: 0.4ms)
ActionView::Template::Error (undefined method `user' for nil:NilClass):
9: <div class="post-container hyphenate">
10: <%= post.body %>
11:
12: <% if signed_in? && @post.user == current_user %>
13:
14: <%= link_to "Edit", edit_post_path(post) %>
15: <%= link_to "Delete", post, method: :delete, data: {confirm: "Are you sure you want to delete this post?"} %>
app/views/posts/index.html.erb:12:in `block in _app_views_posts_index_html_erb__995985056227498542_70346416865540'
app/views/posts/index.html.erb:8:in `_app_views_posts_index_html_erb__995985056227498542_70346416865540'
更改
<% if signed_in? && @post.user == current_user %>
至
<% if signed_in? && post.user == current_user %>
index
页面上没有@post
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.