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
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
2 Comments
user3571908
Thanks, is there a way to make every attribute for the object behave this way instead of adding them one-by-one?
Marcus Ilgner
Just wrap them in a loop:
%w(attr1 attr2).each do |attr| eval "def #{attr}=(new_val) ... end" endWell, 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