Flag invalid attribute in ActiveRecord
Asked Answered
A

1

3

I am trying to implement functionality wherein an attribute, once set, cannot be changed on an ActiveRecord model. To this end, I have written the following methods:

def address
 self[:address]
end

def address=(val)
 if new_record?
  self[:address] = val
 else
  errors.add(:address, "Cannot change address, once it is set")
  return false # tried return nil here first, did not work
 end
end

Am I doing something wrong here? I want the object to be invalid once I try to change an address, but I do not get any errors when I do obj.valid?

EDIT: The value is not changed once it is set, but I would like to get invalid object when I do the validation via obj.valid?

Alexi answered 1/3, 2011 at 19:56 Comment(0)
A
8

When you do obj.valid?, it clears all of your errors, and then runs each of the validations in turn. To have this produce an error on validation, you'll have to move that logic into a validation block.

Here's an example of one way to do that with an instance variable:

def address=(val)
  if new_record?
    self[:address] = val
  else
    @addr_change = true
    return false # tried return nil here first, did not work
  end
end

validate do |user|
  errors.add(:address, "Cannot change address, once it is set") if @addr_change
end
Alsoran answered 1/3, 2011 at 20:0 Comment(3)
Duh! I should have thought of that. Thanks!Alexi
No problem. I added a code example for posterity, in case somebody else comes along asking the same question. :-)Alsoran
Thanks thanks thanks! This is what I was looking for for many hours for my legacy project.Ellynellynn

© 2022 - 2024 — McMap. All rights reserved.