Skip to content

Commit f6077d7

Browse files
committed
Handle association validation on Album model
1 parent 5396829 commit f6077d7

File tree

3 files changed

+38
-0
lines changed

3 files changed

+38
-0
lines changed

app/models/album.rb

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,20 @@
1+
class Album
2+
class Validator < ActiveModel::Validator
3+
4+
ERROR_MESSAGE = 'An album must be associated with an artist.'.freeze
5+
6+
def validate(album)
7+
unless album.title && album.artist && album.artist.persisted?
8+
album.errors.add(:base, ERROR_MESSAGE)
9+
end
10+
end
11+
end
12+
end
13+
114
class Album
215
include ActiveModel::Model
316
include ActiveModel::Validations
17+
validates_with Validator
418

519
ATTRIBUTES = [:id,
620
:artist,

app/repositories/album_repository.rb

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,16 @@ def album_count_by_artist(artist)
2727
count(query: { match: { artist_id: artist.id } })
2828
end
2929

30+
def serialize(album)
31+
album.validate!
32+
album.to_hash.tap do |hash|
33+
hash.merge!(artist_id: album.artist.id)
34+
suggest = { title: { input: [hash[:title]] } }
35+
suggest[:tracklist] = { input: hash[:tracklist].collect(&:strip) } if hash[:tracklist].present?
36+
hash.merge!(:album_suggest => suggest)
37+
end
38+
end
39+
3040
def all(options = {})
3141
search({ query: { match_all: { } } },
3242
{ sort: 'title' }.merge(options))

test/repositories/album_repository_test.rb

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -63,4 +63,18 @@ class AlbumRepositoryTest < ActiveSupport::TestCase
6363
assert @repository.save(album)
6464
assert @repository.find(@repository.save(album)['_id']).is_a?(Album)
6565
end
66+
67+
test 'AlbumRepository #serialize' do
68+
artist = Artist.new(id: 1, name: 'Common')
69+
album = Album.new(title: 'Like Water for Chocolate',
70+
artist: artist,
71+
tracklist: [' The Light ', ' The Questions '],
72+
label: 'MCA')
73+
doc = @repository.serialize(album)
74+
assert doc[:artist].nil?
75+
assert doc[:artist_id] == 1
76+
assert doc[:tracklist] == [' The Light ' , ' The Questions ']
77+
assert doc[:album_suggest][:title] == { input: ['Like Water for Chocolate'] }
78+
assert doc[:album_suggest][:tracklist] == { input: ['The Light', 'The Questions'] }
79+
end
6680
end

0 commit comments

Comments
 (0)