I have a database of objects (tools) in my Ruby on Rails project. When I use “rails dbconsole” and
select * from tools;
it returns a whole list of tool objects. But when I try to view the following page, it gives me an error.
Page:
<!DOCTYPE html>
<html lang="en">
<%= stylesheet_link_tag "tools", :media => "all" %>
<body>
<%= @tools.each do |tool| %>
<%= link_to(tool(image_tag.image_url)) %>
<% end %>
</body>
</html>
Error:
undefined method `each' for nil:NilClass
When I change the code to add an if statement against nil objects, the page works (without displaying any tools).
<% if @tools.nil? %>
<% else %>
<%= @tools.each do |tool| %>
<%= link_to(tool(image_tag.image_url)) %>
<% end %>
<% end %>
So it seems like @tools doesn’t have any values in it, but when I look at it in the dbconsole, there are tools there. I can’t figure this out, and I’ve spent the past few days googling for answers, so any and all ideas would be welcome!
EDIT: Added tools_controller.rb
class ToolsController < ApplicationController
before_filter :check_authentication
def check_authentication
unless session[:user_id]
session[:intended_action] = action_name
session[:intended_controller] = controller_name
redirect_to new_session_url
end
end
def new
@tool = Tool.new
respond_to do |format|
format.html # new.html.erb
format.json { render :json => @tool }
end
end
def show
end
def index
@tools = Tool.all
end
# GET /tools/1/edit
def edit
@tool = Tool.find(params[:id])
end
# POST /tools
# POST /tools.json
def create
@tool = Tool.new(params[:tool])
respond_to do |format|
if @tool.save
format.html { redirect_to @tool, :notice => 'tool was successfully created.' }
format.json { render :json => @tool, :status => :created, :location => @tool }
else
format.html { render :action => "new" }
format.json { render :json => @tool.errors, :status => :unprocessable_entity }
end
end
end
end
In order for the
@toolsvariable to be accessible from your view, you need to declare it in your controller, like this:If you want it to be only accessible from one page, just declare it in the according method.
Here is an example, assuming you want to make the variable available for your
home/indexpage:If you want it to be accessible in all your pages, you can declare it in the
before_filtermethod of yourApplicationController.Here is how to do this: