views:

45

answers:

5

I am trying to pull the name of the Artist from the Albums database. These are my two models

class Album < ActiveRecord::Base

  belongs_to :artist

  validates_presence_of :title
  validates_length_of :title, :minimum => 5
 end

class Artist < ActiveRecord::Base

  has_many :albums

end

And here is the Albums Controller

 def index
 @ albums = Album.all

 respond_to do |format|
   format.html # index.html.erb
   format.xml  { render :xml => @albums }
 end
end

And the View from the index:

<% @albums.each do |album| %>
  <tr>
    <td><%=h album.id %></td>
    <td><%=h album.title %></td>
    <td><%=h album.artist.name %></td>
  </tr
<% end %>

My end result html is coming out like this for the artist field!

#<Artist:0x000001022e4868>   

and if I set it to artist.name I get this:

undefined method `name' for nil:NilClass

What am I doing wrong?

+3  A: 

You need to do something like:

<%=h album.artist.name %>

The way you used it you are displaying whole object, so to speak.

Slobodan Kovacevic
Yes I tried that and I get this, "undefined method `name' for nil:NilClass"
Trip
If for album.artist.name it says that, it means you don't have an artist defined (i.e. artist is nil and nil doesn't have a method name). For easier debugging try dumping album variable - use something like <%= debug album %> or <%= album.to_yaml %>. This will show you what exactly you have.
Slobodan Kovacevic
A: 

Something is going on the saving of your artists->album relationship. If you're getting that error you're getting a nil artist back which means the key isn't being saved in the table. Check your table manually and make sure the relation is there if it's not then you're looking in the wrong place, you should be fixing your save.

JoshReedSchramm
+3  A: 

Sounds like you have an Album without an Artist (either artist_id is null or set to an artist_id that no longer exist).

You can try:

<%= h album.artist ? album.artist.name : 'N/A' %>
Tony Fontenot
A: 

Do you actually have data correctly set up in your database tables? If your Artist and Album models are being saved correctly then it should look something like this:

artists table

id|name
---------------------
 1|The Beatles
 2|The Rolling Stones

albums table

id|artist_id|title
--------------------------------------------------
 1|1        |The White Album
 2|2        |Exile on Main Street
 3|1        |Sgt. Pepper's Lonely Hearts Club Band
John Topley
+1  A: 

Another way to write what was enumerated earlier.

<%= h album.artist.name unless album.artist.blank? %>

I would recommend going into script/console and manually stepping through the process of pulling all your articles and then printing out all the artist names.

BTW, if you're running this code in production you should probably use eager loading

 @ albums = Album.find(:all, :includes => [:artist]) 

This will be much more efficient.

ThinkBohemian