【问题标题】:Undefined Method Nil Class - Simple Model未定义方法 Nil 类 - 简单模型
【发布时间】:2015-10-07 00:44:01
【问题描述】:

我有两个简单的模型,ArtworkArtist。在我的artwork#index 视图中:

<% @artwork.each do |art| %>
    Title: <%= art.title %>
    Artist: <%= art.artist.fullname %>
<% end %>

但我不断收到此错误:

undefined method `fullname' for nil:NilClass

这是一个一对多的关联。在我的Artwork 模特:

class Artwork < ActiveRecord::Base
    belongs_to :artist
    accepts_nested_attributes_for :artist
end

艺人模特:

class Artist < ActiveRecord::Base
    has_many :artworks

    def fullname
        "#{first_name} #{last_name}"
    end
end

非常感谢任何帮助。

【问题讨论】:

  • 您的artworks 表中有artist_id 没有nil 值吗?
  • @Pavan 我刚刚意识到索引中的一些确实具有nil 值。我怎样才能绕过这个异常,或者告诉它即使其中一些有 nil 值仍然呈现?
  • 这应该适用于&lt;%= art.try(:artist).fullname %&gt; 你能再次检查并确认吗?连同@Emu 回答。
  • @Pavan 我遇到了同样的错误。我也试过first_name
  • 我使用了这个:art.artist.fullname if art.artist.present? 并让它工作。你会说这是最简单的方法吗?或者我可以在模型或控制器中做一些其他配置吗?

标签: ruby-on-rails forms associations one-to-many data-modeling


【解决方案1】:
def fullname
    "#{self.first_name} #{self.last_name}"
end

在您的任何artworks 中都没有artist_id。检查artist_id 是否包含任何artworknil 值。

使用,art.artist.present?

【讨论】:

  • 同样的错误,我什至用first_name (&lt;%= art.artist.first_name %&gt;) 尝试过,它实际上是数据库中的一列。
  • 在您的任何artworks 中都没有artist_id。检查artist_id 是否包含任何artworknil 值。
  • 我刚刚意识到其中一些实际上确实具有 nil 值。如果遇到 nil 值,我该如何绕过它或告诉它什么都不打印?
  • 检查是否art.artist.present?
  • pavan 的try 方法是最简单的。但是您应该阅读以下内容:stackoverflow.com/questions/7426808/…
猜你喜欢
  • 1970-01-01
  • 2020-01-03
  • 1970-01-01
  • 2020-04-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多