Created
April 19, 2019 15:50
-
-
Save stephancom/fccca05104a0efa0c8b2c22a34959906 to your computer and use it in GitHub Desktop.
"write once" fields in rails. Can be set on create or ONCE on update, cannot be changed in mass assignment
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
validate :forbid_changing_some_field, on: :update | |
def forbid_changing_some_field | |
return unless some_field_changed? | |
return if some_field_was.nil? | |
self.some_field = some_field_was | |
errors.add(:some_field, 'can not be changed!') | |
end |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
describe 'forbids changing some field once set' do | |
let(:initial_some_field) { 'initial some field value' } | |
it 'defaults as nil' do | |
expect(record.some_field).to be nil | |
end | |
it 'can be set' do | |
expect { | |
record.update_attribute(:some_field, initial_some_field) | |
}.to change { | |
record.some_field | |
}.from(nil).to(initial_some_field) | |
end | |
describe 'once it is set' do | |
before do | |
record.update_attribute(:some_field, initial_some_field) | |
end | |
it 'makes the record invalid if changed' do | |
record.some_field = 'new value' | |
expect(record).not_to be_valid | |
end | |
it 'does not change in mass update' do | |
expect { | |
record.update_attributes(some_field: 'new value') | |
}.not_to change { | |
record.some_field | |
}.from(initial_some_field) | |
end | |
it 'DOES change in update_attribute!! (skips validations' do | |
expect { | |
record.update_attribute(:some_field, 'other new value') | |
}.to change { | |
record.some_field | |
}.from(initial_some_field).to('other new value') | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment