NoMethodError in Book#show_subjects

Hi,

I am quite new to ROR.I am trying to create a rails simple application
that has informations about Books and Subjects.Srangely, I finished
creating a basic application, and it worked fine.
But then , I just tried to add some more values in the database, and
faced problem with migration, that just made me crazy. SO I deleted the
database and did the database and migration thing all over again without
touching rest of the codes.Now the application runs, but when I click on
the subject name, it show error, although it was working well before.Can
someone help me please in this regards ???

The ERROR is :

NoMethodError in Book#show_subjects

Showing book/show_subjects.rhtml where line #1 raised:

You have a nil object when you didn’t expect it!
The error occurred while evaluating nil.name

Extracted source (around line #1):

1:

<%= @subject.name -%>


2:

    3: <% @subject.books.each do |c| %>
    4:
  • <%= link_to c.title, :action => “show”, :id => c.id -%>
  • I have two tables in my database : books and subjects

    The Controller is

    class BookController < ApplicationController
    layout ‘standard’
    def list

@books = Book.find(:all)

end

def show

@book = Book.find(params[:id])

end

def new
@book = Book.new
@subjects = Subject.find(:all)
end

def create
@book = Book.new(params[:book])
if @book.save
redirect_to :action => ‘list’
else
@subjects = Subject.find(:all, :order => “name”)
render :action => ‘new’
end
end

def edit

@book = Book.find(params[:id])
@subjects = Subject.find(:all)

end

def update
@book = Book.find(params[:id])
if @book.update_attributes(params[:book])
redirect_to :action => ‘show’, :id => @book
else
@subjects = Subject.find(:all)
render :action => ‘edit’
end
end

def delete
Book.find(params[:id]).destroy
redirect_to :action => ‘list’
end

def show_subjects
@subjects = Subject.find(params[:id])

end

end

The show_subjects.rhtml file is :

<%= @subject.name -%>

    <% @subject.books.each do |c| %>
  • <%= link_to c.title, :action => "show", :id => c.id -%>
  • <% end %>

end

I don’t know if this is a typo in your post or not, but your
#show_subjects
method sets the “@subjects” (note the plural) instance variable whereas
your
view references the “@subject” (note – singular) instance variable.

–wpd

Thanks a lot Patrick, it works now!!!
thanks a lot.

Patrick D. wrote:

end

I don’t know if this is a typo in your post or not, but your
#show_subjects
method sets the “@subjects” (note the plural) instance variable whereas
your
view references the “@subject” (note – singular) instance variable.

–wpd