0
votes

Showing app/views/car/index.html where line #3 raised:

You have a nil object when you didn't expect it! You might have expected an instance of Array. The error occurred while evaluating nil.each Extracted source (around line #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

what is the problem I dont understand

New error is

SyntaxError in Car#index

Showing app/views/car/index.html.erb where line #20 raised:

compile error C:/Users/Jatinder/BitNami RubyStack projects/mercedes_mod 2/app/views/car/index.html.erb:20: syntax error, unexpected kENSURE, expecting kEND C:/Users/Jatinder/BitNami RubyStack projects/mercedes_mod 2/app/views/car/index.html.erb:22: syntax error, unexpected $end, expecting kEND Extracted source (around line #20):

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

Trace of template inclusion: 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>

New error yet again this time when I go back to add car page:

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
Can you provide more code, please? Where do you assign @cars? - J-_-L
@cars is assigned in the car.controller.rb - Jatinder Singh
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 - Jatinder Singh

1 Answers

1
votes

You need to put the @cars assignment in an index action.

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