Invalid flag attribute in ActiveRecord

I am trying to implement functionality in which the attribute once set cannot be changed in the ActiveRecord model. To this end, I wrote 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 when I try to change the address, but I don't get any errors when I doobj.valid?

EDIT: the value does not change after setting it, but I would like to get an invalid object when I check with obj.valid?

+3
source share
1 answer

obj.valid?, . , .

:

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
+8

Source: https://habr.com/ru/post/1795587/


All Articles