[英]Listing all the songs that are in my favorites? ruby on rails
我在nil:NilClass`的“ Favorites#index undefined method
名称”中收到NoMethodError,我的目标是列出所有添加到收藏夹的歌曲? 我的代码如下:
最喜欢的控制器
class FavoritesController < ApplicationController
include FavoriteHelper
def index
@favorites = Song.all
@songs = Song.all
@songs = current_user.favorites
@top_songs = Favorite.joins("LEFT OUTER JOIN songs ON favorites.song_id = songs.id").select("favorites.*,songs.name as name, songs.artist_id as artist_id").group(:song_id).order('COUNT(songs.id) DESC')
.limit(10)
end
private
def favorites_params
params.require(:favorites).permit(:song_id, :user_id)
end
end
songs_controller.rb
class SongsController < ApplicationController
before_action :find_song, {only: [:edit, :update, :show, :like]}
def index
@songs = Song.all
@songs = Song.search(params[:term]).paginate(:page => params[:page], :per_page => 10).order(created_at: :desc)
@top_songs = Favorite.joins("LEFT OUTER JOIN songs ON favorites.song_id = songs.id").select("favorites.*,songs.name as name, songs.artist_id as artist_id").group(:song_id).order('COUNT(songs.id) DESC')
.limit(10)
@latest_albums = Album.order('created_at DESC').last(5)
end
_song.html.erb
部分,以在收藏夹中呈现歌曲
<% @songs.each do |song| %>
<tr>
<th scope="row"><%= song.id %></th>
<% if logged_in? %>
<td>
<div class="like">
<div class="like-btn text-center" song_id="<%= song.id %>">
<span class="<%= song.heart_class(current_user) %>"></span>
</div>
</td>
<td><%= link_to @song.name, favorite_path(song.id) %></td>
<td>
<a data-toggle="modal" data-target="#addSong" data-id="<%= song.id %>" title="Add this song to playlist" class="open-AddSong" href="#addSong"><i class="fa fa-plus" aria-hidden="true" rel="tooltip" data-placement="top" title="Add to playlist"></i></a>
<div class="modal fade" id="addSong">
<%= render 'shared/add_song_to_playlist' %>
</div>
</td>
<% end %>
</tr>
<% end %>
routes.rb
post '/song:id/like', to: 'songs#like', as: :like
resources :songs
resources :favorites do
resource :songs
end`enter code here`
感谢大家!
首先(与问题无关),在“ favorites#index
操作中,您具有:
@songs = Song.all
@songs = current_user.favorites
第一行是不必要的,并被第二行覆盖。 songs#index
#index中也有类似的问题。
但是,您的问题是局部的,您需要删除@
in:
<%= link_to @song.name, favorite_path(song.id) %>
您没有@song
变量(只有@songs
和song
)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.