Drawing information from relational databases in Rails
Posted
by Trip
on Stack Overflow
See other posts from Stack Overflow
or by Trip
Published on 2010-05-24T18:52:20Z
Indexed on
2010/05/24
20:01 UTC
Read the original article
Hit count: 246
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!
#
and if i set it to artist.name
I get this: undefined method `name' for nil:NilClass
© Stack Overflow or respective owner