如何显示一些帖子选项,仅适用于Rails中帖子的创建者

时间:2016-02-06 20:43:25

标签: html ruby-on-rails ruby activerecord

我收到错误"未定义的方法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

这是我的帖子控制器中的create操作:

def create
        @post = Post.new(post_params)
        @post.user = current_user
        if @post.save
            redirect_to root_path
        else
            render :new
        end
    end

这是我的观点的一部分,我试图&#34;温和&#34;谁有权访问编辑和删除:

<% 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'

1 个答案:

答案 0 :(得分:0)

更改

<% if signed_in? && @post.user == current_user %>

<% if signed_in? && post.user == current_user %>

@post页面上没有index