【问题标题】:Listing all the songs that are in my favorites? ruby on rails列出我最喜欢的所有歌曲?铁轨上的红宝石
【发布时间】:2017-09-17 20:25:45
【问题描述】:

我在 Favorites#index undefined methodname' for nil:NilClass` 中收到 NoMethodError,我的目标是列出所有添加到收藏夹的歌曲?我的代码如下:

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

部分_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`

谢谢大家!

【问题讨论】:

    标签: ruby-on-rails ruby activerecord


    【解决方案1】:

    首先(与问题无关),在您的favorites#index 操作中,您有:

    @songs = Song.all
    @songs = current_user.favorites
    

    第一行是不必要的,并被第二行覆盖。 songs#index 也有类似的问题。

    但是,您的问题是部分问题,您需要删除@ in:

    <%= link_to @song.name, favorite_path(song.id) %>
    

    您没有@song 变量(只有@songssong)。

    【讨论】:

    • 谢谢@Ryan!我已将它们从歌曲和收藏夹控制器中删除。但不幸的是,您的解决方案不起作用。
    猜你喜欢
    • 2011-07-13
    • 2016-01-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-03-26
    • 1970-01-01
    • 2016-04-21
    • 2015-07-16
    相关资源
    最近更新 更多