Car#index中的NoMethodError

时间:2011-05-17 16:33:21

标签: html ruby-on-rails ruby

显示第3行引发的app / views / car / index.html:

当你没想到它时,你有一个零对象! 您可能期望一个Array实例。 评估nil.each时发生错误 提取的来源(第3行):

1:<h2>Current List of Cars</h2>

2:<dl>

3:<% @cars.each do |car| %>

4:<dt><%= car.name %></dt>

5:<dd>

6:<%= car.description %><br />

car_controller.rb:

class CarController < ApplicationController
  def add
      @title = "Add a New Car"

    if request.post?
      @car = Car.new(params[:car])
      @car.user_id = User.logged_in(session).id
    if @car.save
        flash[:notice] = "Car #{@car.name} added!"
        redirect_to :controller => :car, :action => :index
      end
    end
    @cars = Car.find(:all)
  end

  def edit
  end

end

我不明白的问题是什么

新错误

Car#index

中的SyntaxError

显示第20行引发的app / views / car / index.html.erb:

编译错误 C:/ Users / Jatinder / BitNami RubyStack项目/ mercedes_mod 2 / app / views / car / index.html.erb:20:语法错误,意外kENSURE,期待kEND C:/ Users / Jatinder / BitNami RubyStack projects / mercedes_mod 2 / app / views / car / index.html.erb:22:语法错误,意外$ end,期待kEND 提取的来源(第20行):

17: </dl>
18: 
19: <p><%= link_to "Add a Car", :controller => :car, :action => :add %></p>

模板包含跟踪:app / views / car / index.html.erb

/views/car/index.html.erb

<h2>Current List of Cars</h2>
<dl>
<% @cars.each do |car| %>
  <dt><% @user.cars.each do |cars| unless @user.blank? %></dt>
  <dd>
    <%= car.description %><br />
    <%= link_to "Edit", 
          :controller => :car, 
          :action => :edit,
          :id => car.id %> |
    <%= link_to "Delete", 
          :controller => :car, 
          :action => :delete,
          :id => car.id %>
  </dd>
<% end %>
</dl>

<p><%= link_to "Add a Car", :controller => :car, :action => :add %></p>

这次我再回来添加车页时又出现了新的错误:

NoMethodError in Car#add

Showing app/views/car/add.html.erb where line #2 raised:

undefined method `errors' for #<Array:0x57841b0>
Extracted source (around line #2):

1: <h1>Add a New Car</h1>
2: <%= error_messages_for :car %>
3: <% form_for :car do |f| %>
4:   <p>
5:     <%= f.label :name %>:

1 个答案:

答案 0 :(得分:1)

您需要将@cars作业置于index行动中。

def index
  @cars = @user ? @user.cars : Car.all
end