Skip to content

Commit

Permalink
Allow plays to be scoped by album (#245)
Browse files Browse the repository at this point in the history
  • Loading branch information
robbevp authored Aug 22, 2021
1 parent 87b1f6e commit 478d7e5
Show file tree
Hide file tree
Showing 4 changed files with 19 additions and 0 deletions.
2 changes: 2 additions & 0 deletions app/controllers/plays_controller.rb
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
class PlaysController < ApplicationController
has_scope :by_album, as: 'album_id'

def index
authorize Play
@plays = apply_scopes(policy_scope(Play))
Expand Down
2 changes: 2 additions & 0 deletions app/models/play.rb
Original file line number Diff line number Diff line change
Expand Up @@ -12,4 +12,6 @@ class Play < ApplicationRecord
belongs_to :user

validates :played_at, presence: true

scope :by_album, ->(album) { joins(:track).where(track: { album_id: album }) }
end
10 changes: 10 additions & 0 deletions test/controllers/plays_controller_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,16 @@ class PlaysControllerTest < ActionDispatch::IntegrationTest
assert_empty body
end

test 'should get index with album scope' do
play1 = create(:play, track: @track, user: @user)
play2 = create(:play, user: @user)
get plays_url(album_id: @track.album_id)
assert_response :success
body = JSON.parse response.body
assert_includes body, play1.as_json
assert_not_includes body, play2.as_json
end

test 'should create play' do
assert_difference('Play.count', 1) do
post plays_url, params: { play: { played_at: DateTime.current, track_id: @track.id } }
Expand Down
5 changes: 5 additions & 0 deletions test/models/play_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -10,4 +10,9 @@
require 'test_helper'

class PlayTest < ActiveSupport::TestCase
test 'should be able to filter by album' do
@play = create(:play)
assert_includes Play.by_album(@play.track.album_id), @play
assert_empty Play.by_album(@play.track.album_id + 1)
end
end

0 comments on commit 478d7e5

Please sign in to comment.