开发者

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开发者_Go百科_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?


You need to do something like:

<%=h album.artist.name %>

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


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' %>


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.


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


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜