【问题标题】:Drawing information from relational databases in Rails在 Rails 中从关系数据库中提取信息
【发布时间】:2011-02-23 08:58:21
【问题描述】:

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

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

我做错了什么?

【问题讨论】:

  • 专辑控制器中 @ 和专辑之间的空格是这里的错字还是在您的代码中?

标签: ruby-on-rails sqlite sqlite3-ruby


【解决方案1】:

您需要执行以下操作:

<%=h album.artist.name %>

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

【讨论】:

  • 是的,我试过了,我得到了这个,“nil:NilClass 的未定义方法‘名称’”
  • 如果对于 album.artist.name 它说,这意味着你没有定义艺术家(即艺术家是 nil 并且 nil 没有方法名称)。为了更容易调试,请尝试转储专辑变量 - 使用 或 之类的东西。这会告诉你你到底有什么。
【解决方案2】:

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

你可以试试:

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

【讨论】:

    【解决方案3】:

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

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

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

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

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

    这样会更有效率。

    【讨论】:

      【解决方案4】:

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

      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
      

      【讨论】:

        【解决方案5】:

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

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2019-09-06
          • 2023-04-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多