Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Ruby

Jordan Aldujaili
Jordan Aldujaili
5,852 Points

An empty Array in the API - json

Hi, I am using postman to receive json from an API that I am creating. I don't get an error, but the index is not behaving the way I want it to. What I want is for the index to have a current playlist and only render the songs that are in that specific playlist. I have data in the database, yet I am getting an empty array. I think it may have to do with the relationships, but I am not sure. Any ideas? Thanks

class Api::V1::PlaylistSongsController < ApplicationController
def index
  @playlist_song = current_playlist.playlist_songs
    render json: @playlist_song
end

class ApplicationController < ActionController::Base
def current_playlist
    @current_playlist ||= Playlist.where({user_id: current_user.id}).first
end

class Playlist < ActiveRecord::Base
  has_many :playlist_songs
  has_many :songs, through: :playlist_songs
end

class PlaylistSong < ActiveRecord::Base
#I added a join table because a song should have the ability to have_many playlists
#I just added the foreign_key and inverse_of, but no luck
  belongs_to :playlist, foreign_key: "playlist_id", inverse_of: :playlist_songs
  belongs_to :song    , foreign_key: "song_id", inverse_of: :playlist_songs
end

class Song < ActiveRecord::Base
  has_many    :playlist_songs
  has_many    :playlists, through: :playlist_songs
end

1 Answer

Jordan Aldujaili
Jordan Aldujaili
5,852 Points

ok, I got it. I just didn't pass in the playlist params.

def current_playlist
    @current_playlist ||= current_user.playlists.find(params[:playlist_id])
  end