1

我正在尝试从专辑数据库中提取艺术家的姓名。这是我的两个模型

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

这是专辑控制器

 def index
 @ albums = Album.all

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

以及来自索引的视图:

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

对于艺术家领域,我的最终结果 html 就是这样出来的!

#<Artist:0x000001022e4868>   

如果我将它设置为artist.name 我得到这个:

undefined method `name' for nil:NilClass

我究竟做错了什么?

4

5 回答 5

3

您需要执行以下操作:

<%=h album.artist.name %>

可以这么说,您使用它的方式是显示整个对象。

于 2010-05-24T18:55:50.713 回答
3

听起来你有一个没有艺术家的专辑(艺术家 ID 为空或设置为不再存在的艺术家 ID)。

你可以试试:

<%= h album.artist ? album.artist.name : 'N/A' %>
于 2010-05-24T19:53:59.077 回答
1

另一种编写前面列举的内容的方法。

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

我建议进入脚本/控制台并手动逐步完成提取所有文章然后打印出所有艺术家姓名的过程。

顺便说一句,如果您在生产中运行此代码,您可能应该使用急切加载

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

这将更有效率。

于 2010-05-24T21:42:05.493 回答
0

正在拯救你的艺术家->专辑关系。如果您遇到该错误,您将获得一个 nil 艺术家,这意味着密钥没有保存在表中。手动检查您的表并确保关系存在,如果不是,那么您在寻找错误的地方,您应该修复您的保存。

于 2010-05-24T19:53:40.760 回答
0

您实际上是否在数据库表中正确设置了数据?如果您的艺术家和专辑模型被正确保存,那么它应该如下所示:

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
于 2010-05-24T19:55:03.550 回答