Search code examples
ruby-on-railsruby-on-rails-4updatesupdate-attributes

detect if only one attribute is updated in Rails 4 on update_attributes


I am making a blogging app. I need to have two different methods based on how many attributes have been changed. Essentially, if ONLY the publication_date changes I do one thing...even the publication_date and ANYTHING ELSE changes, I do another thing.

posts_controller.rb

def special_update
  if #detect change of @post.publication_date only
    #do something
  elsif # @post changes besides publication_date
  elsif #no changes
  end
end

Solution

  • One way to approach this is in your model using methods provided by ActiveModel::Dirty, which is available to all your Rails Models. In particular the changed method is helpful:

    model.changed # returns an array of all attributes changed. 
    

    In your Post model, you could use an after_update or before_update callback method to do your dirty work.

    class Post < ActiveRecord::Base
      before_update :clever_method
    
      private 
      def clever_method
        if self.changed == ['publication_date'] 
          # do something 
        else 
          # do something else 
        end
      end
    end