Skip to content

Instantly share code, notes, and snippets.

@ArmandoAssuncao
Last active February 9, 2021 13:48
Show Gist options
  • Save ArmandoAssuncao/4bb1d366cf6c8c8fff56fce1af70893c to your computer and use it in GitHub Desktop.
Save ArmandoAssuncao/4bb1d366cf6c8c8fff56fce1af70893c to your computer and use it in GitHub Desktop.
Sets read only to field non nil in MongoId
> user = User.new
> user.username
=> nil
> user.username = 'kira'
=> "kira"
> user.username = 'kira'
=> "kira"
> user.username = 'Light'
Mongoid::Errors::Validations:
message:
Validation of User failed.
summary:
The following errors were found: username is readonly
resolution:
Try persisting the document with valid data or remove the validations.
> user.save
=> true
> user.update!(username: 'another')
Mongoid::Errors::Validations:
message:
Validation of User failed.
summary:
The following errors were found: username is readonly
resolution:
Try persisting the document with valid data or remove the validations.
class User
include Mongoid::Document
include Mongoid::Timestamps
field :username, type: String
field :actived, type: Boolean, default: true
# set readonly when the field is not more nil
def username=(new_value)
msg_error = 'is readonly'
is_readonly = !self.username.nil? && self.username != new_value
self.errors.add(:username, msg_error) if is_readonly && !self.errors.added?(:username, msg_error)
raise Mongoid::Errors::Validations, self if is_readonly
super(new_value)
end
# field with default
def actived=(new_value)
msg_error = 'is readonly'
is_readonly = !self.actived.nil? && self.actived != new_value
is_readonly &&= self.actived != self.fields[:actived.to_s].default_val # check if is different of default
self.errors.add(:actived, msg_error) if is_readonly && !self.errors.added?(:actived, msg_error)
raise Mongoid::Errors::Validations, self if is_readonly
super(new_value)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment