如何修复 haml 中的这个名称错误?

How to fix this name error in haml?

我在 Udemy 上看课程,他们在 index.html.haml 下写了以下代码:

@docs.each do |doc|
%h2= link_to doc.title, doc
%p= time_ago_in_words(doc.created_at)
%p= truncate(doc.content, length:50)

当我在 Chrome 上保存并加载它时,我收到以下消息:

NameError in Docs#index Showing /Users/mac/Documents/Projects/Web
Development/Ruby On Rails/cabinet/app/views/docs/index.html.haml where
line #2 raised:

undefined local variable or method `doc' for
#<#<Class:0x007fd066675708>:0x007fd0663b0900> Did you mean?  doc_url
               @docs

这里有什么问题?这是我的第一个项目,如果你能编辑我的代码,并为初学者解释一下,我将不胜感激。如果需要任何其他文件,请告诉,会给。

感谢阅读。 :)

docs_controller.rb

class DocsController < ApplicationController
  before_action :find_doc, only: [:show, :edit, :update, :destroy]


def index
  @docs = Doc.all.order("created_at DESC")
end

def show

  end

def new
  @doc = Doc.new
end


def create
  @doc = Doc.new(doc_params)

  if @doc.save
    redirect_to @doc

  else
    render 'new'
  end
end

def edit
end


def update
  end


def destroy
end


private

  def find_doc
    @doc = Doc.find(params[:id])
  end

  def doc_params
    params.require(:doc).permit(:title, :content)
  end




end

index.html.haml

@docs.each do |doc|
%h2= link_to doc.title, doc
%p= time_ago_in_words(doc.created_at)
%p= truncate(doc.content, length:50)

routes.rb

Rails.application.routes.draw do
  get 'welcome/index'

  # For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html

  root 'welcome#index'

  resources :docs

end

您似乎没有在每个循环块中正确嵌套要执行的内容,它应该如下所示:

- @docs.each do |doc|
  %h2= link_to doc.title, doc
  %p= time_ago_in_words(doc.created_at)
  %p= truncate(doc.content, length:50)

但是如果你像这样嵌套它:

  - @docs.each do |doc|
  %h2= link_to doc.title, doc

每个块将被执行(此处无事可做),然后通过尝试访问仅为每个块定义的 local/method doc 来呈现 h2