Search code examples
ruby-on-railssqlitesqlite3-ruby

Drawing information from relational databases in Rails


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?


Solution

  • 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.