如何在haml中修复此名称错误?

时间:2016-09-08 10:31:19

标签: ruby-on-rails haml nameerror

我正在观看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

1 个答案:

答案 0 :(得分:1)

好像你没有正确地嵌套你想要在每个循环块中执行的内容,它应该看起来像:

- @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

将执行每个块(此处无需执行任何操作),然后通过尝试访问仅为每个块定义的本地/方法doc来呈现h2