I am new to Ruby on Rails and im stuck on something so simple but I just cant figure it out.
I scaffolded a Video model, controller and view and then created a Welcome controller for the home page.
I manually created an index.html.erb file in the welcome view folder and proceeded to route the home page to Welcome#index. All working fine for now.
Thing is when I define a method in the welcome_controller like this
def foo
puts 'Hello'
end
and I call it in the welcome/index.html file like this
<%= foo %>
I get the following error: undefined local variable or method `foo' for #<#:0x39675d8>
Controller actions aren't view helpers, you'll want to put foo
in either application_helper.rb
or welcome_helper.rb
to use it like you are and change it to remove the puts
, like this:
def foo
'Hello'
end
This will insert Hello
into your view (which is what I think you were expecting)
Based on your comments below, you should probably be using a scope
in your model...
scope :highlighted -> { (where(highlight: true) }
... to return highlighted records from your controller...
@highlighted = Videos.highlighted
... and then iterate over @highlighted in your view...
<% @highlighted.each do |video| %>
<%= ...do something with video here... %>
<% end %>
please read more about all this here:
http://guides.rubyonrails.org/index.html
and specificially for scopes here...
You can't call arbitrary "things" in the controller.
What's exposed in the controller are its instance variables, eg, @foo
.
If you really want to call a method that uses puts
, put it in a helper, eg, welcome_helper.rb
(or whatever the convention would be).
Note, however, that this won't do what you appear to believe it will, namely, put a "Hello" on the web page. You're basically writing directly to the console, not even the log file.
What specifically are you trying to accomplish?
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.