Scarlet McLearn
Scarlet McLearn

Reputation: 71

How to fix this name error in haml?

I was watching the course on Udemy, where they wrote the following code under 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)

When I saved and loaded it on Chrome, I got the following message :

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

What is wrong here? This is my first project, so would appreciate if you could edit my code, and, explain it for a beginner. If any other files are required, do tell, will give.

Thanks for the read. :)

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

Upvotes: 0

Views: 252

Answers (1)

jethroo
jethroo

Reputation: 2124

seems like you haven't nested the content which you want to have executed in the each loop block properly, it should look like:

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

but if your are nesting it like:

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

the each block will be executed (nothing to do here) and thereafter the h2 is rendered by trying to access the local/method doc which is only defined for the each block

Upvotes: 1

Related Questions