-
-
Save ArmandoAssuncao/4bb1d366cf6c8c8fff56fce1af70893c to your computer and use it in GitHub Desktop.
Sets read only to field non nil in MongoId
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
> 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. |
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
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