【问题标题】:ActionView::Template::Error (no implicit conversion of nil into String)ActionView::Template::Error(没有将 nil 隐式转换为 String)
【发布时间】:2014-05-29 18:27:37
【问题描述】:

我以前从未遇到过这样的错误,不知道如何摆脱它。

ActionView::Template::Error (no implicit conversion of nil into String)
...
24: <p>Genre:<%= link_to @movie.genre, "movies?genre=" + @movie.genre.to_s %></p>
....
app/views/movies/show.html.erb:24:in `+'

【问题讨论】:

  • @movie 是一个集合吗?我猜@movie 是零。
  • 不,它不是,只是一个对象(我想这就是它的名字......)。

标签: ruby-on-rails ruby ruby-on-rails-4


【解决方案1】:

您需要能够处理可能的 nil 值。将您的代码更改为:

<p>Genre:<%= link_to @movie.try(:genre), "movies?genre=" + @movie.try(:genre) %></p>

由于整个链接取决于流派,您甚至可以这样做:

<p>Genre:<%= link_to @movie.try(:genre), "movies?genre=" + @movie.try(:genre) if @movie.genre %></p>

【讨论】:

    【解决方案2】:

    可能@movie.genre 为零。

    所以,当您尝试@movie.genre.to_s 时,您实际上是在这样做:

    nil.to_s
    

    这是做不到的。

    所以你应该这样做:

    <% if @movie && @movie.genre %>
      <p>Genre:<%= link_to @movie.genre, "movies?genre=" + @movie.genre.to_s %></p>
    <% end %>
    

    【讨论】:

    • 在我输入.to_s 之前出现了错误,我认为这会解决它,但它没有。
    猜你喜欢
    • 1970-01-01
    • 2013-08-04
    • 1970-01-01
    • 2016-02-14
    • 2016-11-25
    • 1970-01-01
    • 1970-01-01
    • 2018-07-08
    • 2019-02-26
    相关资源
    最近更新 更多