我是新手,写了一个类似于 Reddit 的应用程序,我得到的错误是:undefined method `user' for #<Topic

I am novice, writing an app similar to Reddit, and the error I get is: undefined method `user' for #<Topic

NoMethodError in Topics#show

Showing /Users/Tish/code/bloccit/app/views/topics/show.html.erb where line #37 raised:

undefined method `user' for # Extracted source (around line #37):

34  <%= link_to "New Post", new_topic_post_path(@topic), class: 'btn btn-success' %>  
35  <% end %>
36
37  <% if policy(@topic).destroy? %>
38  <%= link_to "Delete Topic", @topic, method: :delete, class: 'btn btn-     danger', 
         data: { confirm: 'Are you sure you want to delete this topic?' } %> 
         <% end %>

here is schema.rb:

ActiveRecord::Schema.define(version: 20150128034556) do

  create_table "comments", force: true do |t|
t.text     "body"
t.integer  "post_id"
t.datetime "created_at"
t.datetime "updated_at"
t.integer  "user_id"
  end

  add_index "comments", ["post_id"], name: "index_comments_on_post_id"
  add_index "comments", ["user_id"], name: "index_comments_on_user_id"

model/user.rb:

class User < ActiveRecord::Base
  devise :database_authenticatable, :registerable,
     :recoverable, :rememberable, :trackable, :validatable, :confirmable

  has_many :posts
  has_many :comments 

  mount_uploader :avatar, AvatarUploader

  def admin?
   role == 'admin'    
  end

 def moderator?
  role == 'moderator'
 end

end

model/comment.rb

   class Comment < ActiveRecord::Base
    belongs_to :post
    belongs_to :user

    default_scope -> { order(created_at: :desc) }

end  

The problem shows when I click on a topic, I get an error. Please excuse me ahead of time for not formatting the question correctly!

here is one of the policies:

   class TopicPolicy < ApplicationPolicy

   def index?
    true
   end

   def create?
    user.present? && user.admin?
   end

   def update?
    create?
   end

   def destroy?
    user.present? && can_moderate?(user, record)
   end
 end

要使用方法 user,您需要自己创建它或在模型中添加 belongs_to :user。在这种情况下,由于您的 destroy 方法称为 user,因此它出错了,因为它不知道该怎么做

下次尝试围绕您的错误添加更多详细信息,例如行号或相关 models/controllers。您的编辑使您的问题看起来好多了,干得好。