0

I have an ActiveRecord object with multiple attributes that are allowed to be nil on creation and can later be updated by the user through a form. However, once an attribute is changed from nil to non-nil, that attribute may not be updated again. How should I go about setting up this behavior?

2 Answers 2

1
create_table :funky do |t|
  t.integer :fireflies
end

class Funky < ActiveRecord::Base
  def fireflies=(ff)
    raise "Uh uh.. it was already set" unless self.fireflies.blank?

    write_attribute(:fireflies, ff)
  end
end

Editing post as user requested that many fields be edited

[:one, :two, :three].each do |s|
  define_method "#{s}=" do |v|        
    raise "Uh uh.. it was already set" unless self.send(s).blank?

    write_attribute(s, v)
  end
end
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks, is there a way to make every attribute for the object behave this way instead of adding them one-by-one?
Just wrap them in a loop: %w(attr1 attr2).each do |attr| eval "def #{attr}=(new_val) ... end" end
0

Well, I think you should definitely allow users to change their information at any time, but anyway, if you want to add the restriction to the controller instead of the model you could do this:

def update
  your_model = YourModel.find(params[:id])

  # find the attributes with nil values:
  nil_attributes = your_model.attributes.select {|k,v| v.nil?}.keys.map(&:to_sym)

  # attributes that you allow to edit:
  allowed_attributes = [:title, :description, :size]

  # tell rails which are the allowed modifications:
  allowed_params = params.require(:your_model).permit(*(allowed_attributes - nil_attributes))

  # save the changes:
  your_model.update_attributes(allowed_params)

  # ...
end

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.