Jane
Jane

Reputation: 119

Validation similar to attr_readonly, but ignoring blank attributes

I'm trying to make it so that columns can be filled and updated only if they are blank. Similar to attr_readonly but permitting updates if the attribute is empty.

Here's my sad attempt, it fails because before_update tries to call attr_readonly on the instance.

before_update :check_attrs

def check_attrs
  if column_1.present?
    attr_readonly :column_1
  elsif column_2.present?
    attr_readonly :column_2
  elsif column_3.present?
    attr_readonly :column_3
  elsif column_4.present?
    attr_readonly :column_4
  end
end

Upvotes: 2

Views: 341

Answers (1)

Lucas Nelson
Lucas Nelson

Reputation: 2551

I'm going to assume we are talking about a 'model' class that extends ActiveRecord::Base

My idea is to use validations to enforce the rule: cannot set a value unless the original value was blank.

Though a different question, this helped: Pass field name as parameter to custom validation method Rails 4

API doc for validates_each:

validates_each :column_1, :column_2, :column_3, :column_4 do |record, attr, value|
  attr_was_present = record.changed_attributes[attr].present?
  record.errors.add(attr, 'can only change if blank') if attr_was_present
end

PS: that can be a one-liner, I've added a local variables to (hopefully) add a bit of clarity.

What this will do is add a 'can only change if blank' error to the list of errors of any attribute where an attempt is made to change it. The save will then fail and the database record will not change.

Upvotes: 1

Related Questions