Reputation: 3938
Imagine I have a boolean and a string attribute on my model with data like this:
Model.locked => true
Model.status => "Available"
When the Update action is invoked, I want to use the boolean attribute to control whether the string attribute gets modified by the update, all other attributes in the update should be saved regardless.
So if
Model.locked => true
and we try
Model.status = "Sold"
then
Model.status => "Available"
Currently I have my model like this...
before_update :dont_update_locked_item, :if => :item_locked?
def item_locked?
self.locked
end
def dont_update_locked_item
#Some rails magic goes here
end
How do I prevent a single attribute from being updated?
I know the answer is going to hurt, but someone help me out. It's late, I'm tired and I'm fresh out of talent. ;-)
Upvotes: 0
Views: 311
Reputation: 64363
Try this:
class Item < ActiveReocrd::Base
def mass_assignment_authorizer
super + (locked? ? [] : [:status])
end
end
Reference:
Upvotes: 0
Reputation: 6623
Hope it doesn't hurt so much :)
class Item < ActiveRecord::Base
validate :cannot_update_if_locked, :on => :update
def item_locked?
self.locked
end
def cannot_update_if_locked
errors.add(:item_id, "is locked") if item_locked?
end
end
Upvotes: 2