0

我的 Ruby on Rails 项目中有一个对象(工具)数据库。当我使用“rails dbconsole”和

select * from tools;

它返回工具对象的完整列表。但是当我尝试查看以下页面时,它给了我一个错误。

页:

 <!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>

错误:

undefined method `each' for nil:NilClass

当我更改代码以添加针对 nil 对象的 if 语句时,页面可以正常工作(不显示任何工具)。

<% if @tools.nil? %>
<% else %>
  <%= @tools.each do |tool| %>
    <%= link_to(tool(image_tag.image_url)) %>
    <% end %>
<% end %> 

所以看起来@tools 里面没有任何值,但是当我在 dbconsole 中查看它时,那里有工具。我无法弄清楚这一点,过去几天我一直在谷歌上搜索答案,所以欢迎任何和所有想法!

编辑:添加 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
4

2 回答 2

2

正如@nbarraille 所建议的那样,为每个动作加载@tools一个 before_filter是一个坏主意,因为有许多(可能是大多数)动作你肯定不需要全套工具(例如和)。该行命中您的数据库,因此您应该尽量减少使用它的次数。createdestroy@tools = Tool.all

对于您在此处的情况,您只需更改您的show操作即可使其正常工作:

def show
  @tools = Tool.all
end

However, note that normally the show action is for displaying a single resource (tool), not the whole list of resources (which is normally done in the index action). It looks like you're deviating from the normal way of doing things, is there any particular reason why?

于 2012-09-20T00:29:57.000 回答
1

为了使@tools变量可以从您的视图中访问,您需要在控制器中声明它,如下所示:

@tools = Tool.all

如果您希望它只能从一个页面访问,只需在相应的方法中声明它。

这是一个示例,假设您想让变量可用于您的home/index页面:

class HomeController < ApplicationController

  def index
     @tools = Tool.all

    respond_to do |format|
      format.html # index.html.erb
    end
  end
end

如果您希望它可以在您的所有页面中访问,您可以在before_filter您的ApplicationController.

以下是如何做到这一点:

class ApplicationController < ActionController::Base
  protect_from_forgery
  before_filter :load_variables

  # Load variables to be used everywhere
  def load_variables
    @tools = Tool.all
  end
end
于 2012-09-20T00:09:00.947 回答