assignable_values 0.11.0 can return *intended* assignable values

Posted Almost 10 years ago. Visible to the public.

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

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.

Dominik Schöler
Last edit
Almost 10 years ago
License
Source code in this card is licensed under the MIT License.
Posted by Dominik Schöler to makandra dev (2014-06-10 15:06)