Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Undefined local variable / no method error in Ruby on Rails

Can anyone explain to me why I am getting this error? Rails is about conventions. Is there a more conventional way of doing what I'm trying to do below?

undefined local variable or method `hello_world' for #<#<Class:...>:...>

Here are my files:

welcome_controller.rb

class WelcomeController < ApplicationController
  def hello_world
    "Hello, World"
  end
end

welcome/index.html.erb

<%= hello_world %>

routes.rb

Rails.application.routes.draw do
  get 'welcome/index'
  root 'welcome#index'
end
like image 215
TyLeisher Avatar asked May 01 '14 20:05

TyLeisher


3 Answers

Or do as :

class WelcomeController < ApplicationController
 helper_method :hello_world
 def hello_world
    "Hello, World"
 end
end

Now call it inside the view :

<%= hello_world %>

Read helper_method

Declare a controller method as a helper, to make the hello_world controller method available to the view.

like image 80
Arup Rakshit Avatar answered Oct 17 '22 01:10

Arup Rakshit


You can use a helper to allow you to write that in your ERB:

module WelcomeHelper

  def hello_world
     "Hello, World"
  end

end

and now, your ERB should work:

<%= hello_world %>
like image 44
Uri Agassi Avatar answered Oct 17 '22 03:10

Uri Agassi


hello_world is action defined in controller and routes You need to define variable(s) in your action. This variable(s) will be accessible in the view

class WelcomeController < ApplicationController

 # this is action
 def index
    # this is variable
    @hello_world = "Hello, World"
 end

end

# view index.html.erb
# this calls variables defined in action
<%= @hello_world %>

Update1:

And if you define your route to welcome#index the action name in controller should be index!

like image 2
gotva Avatar answered Oct 17 '22 02:10

gotva