如何通过歌曲控制器中的关联来显示流派?

时间:2013-08-09 00:26:06

标签: ruby-on-rails

如果你去www.leapfm.com,你会看到每首歌的右侧括号内有一个youtube url。在衡量反馈之后,我决定在括号中显示类型标签。

尝试这样做时,

我收到此错误:

Couldn't find Genre without an ID
Extracted source:

def genre_name
@genre = Genre.find(params[:id])
end
def get_last_song

song_controller snippit

def index
      if params[:query].present? 
      @songs = Song.search(params)
      get_last_song
      genre_name
    elsif params[:genre]
      @songs = Song.tagged_with(params[:genre]).paginate(:page => params[:page], :per_page => 15)
      get_last_song
      genre_name
    else      
      @songs = Song.order('id').order('plusminus desc nulls last').paginate(:page => params[:page], :per_page => 15) 
      #@songs = Song.tally.paginate(:page => params[:page], :per_page => 15)
      get_last_song
      genre_name
    end
  end

  def genre_name
    @genre = Genre.find(params[:id])
  end

index.html.erb(_song partial)snippit

<div class="title">
  <%=link_to image_tag('arrow.gif'), vote_for_song_path(song), :remote => true, :method => :put  if controller.action_name == "index" %>
  <%= link_to song.title, song %><span class="subtext"> (<%= song.genre_name %>)</span>
</div>

song.rb snippit:

班级歌曲&lt;的ActiveRecord ::基

acts_as_voteable

  belongs_to :user
  has_many :comments, :dependent => :destroy
  has_many :genre_songs
  has_many :genres, through: :genre_songs

genre.rb

class Genre < ActiveRecord::Base
  has_many :genre_songs, :dependent => :destroy
  has_many :songs, through: :genre_songs

end

架构snippit

 create_table "genre_songs", force: true do |t|
    t.integer  "genre_id"
    t.integer  "song_id"
    t.datetime "created_at"
    t.datetime "updated_at"
  end

  add_index "genre_songs", ["genre_id"], name: "index_genre_songs_on_genre_id", using: :btree
  add_index "genre_songs", ["song_id"], name: "index_genre_songs_on_song_id", using: :btree

  create_table "genres", force: true do |t|
    t.string   "name"
    t.datetime "created_at"
    t.datetime "updated_at"
  end

  create_table "songs", force: true do |t|
    t.string   "title"
    t.string   "artist"
    t.text     "url"
    t.string   "track_file_name"
    t.string   "track_content_type"
    t.integer  "track_file_size"
    t.datetime "track_updated_at"
    t.integer  "user_id"
    t.datetime "created_at"
    t.datetime "updated_at"
    t.integer  "plusminus"
  end

1 个答案:

答案 0 :(得分:1)

你需要摆脱gendre_name方法,因为它没有给你你想要的。你已经将@songs分配给某些歌曲列表,因此很可能在你看来的某个地方就像是:

<% @songs.each do |song| %>
   # display song row
<% end %>

如果是这样,请在每个“循环”中使用如下所示:

(<%= song.genres.map(&:names).join(', ') %>)