Search code examples
ruby-on-railsruby-on-rails-3validationruby-on-rails-3.1before-filter

Using a boolean attribute as a conditional on an update action on a model in Rails 3


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. ;-)


Solution

  • 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