Read more

assignable_values 0.11.0 can return *intended* assignable values

Dominik Schöler
June 10, 2014Software engineer at makandra GmbH

As you know, assignable_values does not invalidate a record even when an attribute value becomes unassignable. See this example about songs:

class Song < ActiveRecord::Base
  belongs_to :artist
  belongs_to :record_label

  assignable_values_for :artist do
    record_label.artists
  end
end
Illustration book lover

Growing Rails Applications in Practice

Check out our e-book. Learn to structure large Ruby on Rails codebases with the tools you already know and love.

  • Introduce design conventions for controllers and user-facing models
  • Create a system for growth
  • Build applications to last
Read more Show archive.org snapshot

We'll create two record labels with one artist each and create a song for one artist. When we change the song's record label, its artist is still valid.

makandra = RecordLabel.create! name: 'makandra records'
dominik = Artist.create! name: 'dominik', record_label: makandra
apple = RecordLabel.create! name: 'apple music'
steve = Artist.create! name: 'steve', record_label: apple

song = Song.create! name: 'gem session', artist: dominik, record_label: makandra
song.assignable_artists = [dominik]
song.record_label = apple
song.assignable_artists = [steve, dominik] # dominik has legacy rights!
song.valid? # => true

When you are trying to find the intended assignable values for that song, dominik is unexpected because he is no artist of the apple record label.

Cure

assignable_values 0.11.0 introduces an option that does what you need:

song.assignable_artists(include_old_value: false) # => [steve]

This may be needed when updating a select field via AJAX, where it is not about validating but displaying valid choices.

Posted by Dominik Schöler to makandra dev (2014-06-10 17:06)