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
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.
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 %>
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
!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With