0

我在我的 Ruby on Rails 应用程序中遇到了一些问题。
这是我的模型:

class Song < ActiveRecord::Base

  attr_accessible :duration, :title, :track_URL, :genre, :image_url

end

我在songs控制器中创建了一个新方法:

def genre
    @songs = Song.find_all_by_genre(params[:id])
    @genre = (params[:id])

    respond_to do |format|
      format.html # index.html.erb
      format.json {render json: @songs}
    end
  end

这是我的部分视图,它动态显示所有类型并使它们可供选择:

<% @songs = Song.select('DISTINCT genre')%>
<li>
    <% @songs.each do |g| %>
        <a href="/genre/<%= g.genre %>"><%= g.genre %></a>
    <% end %>
</li>

直到这里一切正常,但是当我选择一种流派而不是渲染songs/genre.html.erb视图中的所有歌曲时,它给了我一个我无法理解的错误,因为我在控制器中有方法

NoMethodError in Songs#genre

Showing C:/Sites/OML/app/views/songs/genre.html.erb where line #3 raised:

undefined method `each' for nil:NilClass
Extracted source (around line #3):

1: <h2><%= @genre %></h2>
2: 
3: <% @songs.each do |song| %>
4:     <%= song.title %>
5:     <%= song.genre %>
6: <% end %>

我在一个全新的应用程序及其工作中尝试了同样的方法!!我的问题可能出在哪里?

4

1 回答 1

0

改变你的部分来检查是否真的有任何歌曲,像这样

<li>
  <% if @songs %>
    <% @songs.each do |g| %>
      <a href="/genre/<%= g.genre %>"><%= g.genre %></a>
    <% end %>
  <% else %>
    No songs
  <% end %>
</li>

也改变genre.html.erb

<% if @songs %>
  <% @songs.each do |song| %>
    <%= song.title %>
    <%= song.genre %>
  <% end %>
<% else %>
  No Songs
<% end %>
于 2013-05-06T11:01:02.490 回答