I'm getting NoMethodError in Favorites#index undefined method
name' for nil:NilClass` , and my goal is to list all the songs that are added to favorites? My code below:
favorite_controller
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
partial _song.html.erb
to render songs in favorites
<% @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`
Thanks everyone!
First off (not related to the question), in your favorites#index
action, you have:
@songs = Song.all
@songs = current_user.favorites
The first line is unnecessary and is overridden by the second line. A similar issue is in songs#index
.
However, the problem to your question is in the partial, you need to remove the @
in:
<%= link_to @song.name, favorite_path(song.id) %>
You don't have a @song
variable (only @songs
and song
).
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.