开发者

Rail dirty and date changes

开发者 https://www.devze.com 2023-02-23 06:45 出处:网络
Have a column in orders called closed_date which is a DateTime field. Using Dirty.trying to do if self.closed_date_changed? but it\'s not working. Do I have to do something special for tracking chang

Have a column in orders called closed_date which is a DateTime field.

Using Dirty. trying to do if self.closed_date_changed? but it's not working. Do I have to do something special for tracking changes with Date Time fields?


EDIT Using Rails 3.0.3, Ruby 1.9.2p136

Code in orders controller

def update
 @order = Order.find(params[:id])
  if @order.update_attributes(params[:order])
    @order.close_order
  end
 end
end

In Model

includ开发者_开发问答e ActiveModel::Dirty

def close_order
  if self.closed?
    if self.closed_date_changed?
      self.items.each do |item|
        item.update_attribute(:created_at, self.closed_date)
      end
    end
  else
    self.update_attributes(:closed_date => Time.now, :closed => true)
    self.items.each do |item|
       item.update_attribute(:created_at => Time.now)
          item.schedule_any_tasks
        end
    end
  end
end


I think you mean something like:

def save_changes
  if closed_date_changed?
    # do something like save the modified data to a table
  else
    # do anything else
  end
end

And the most important, don't forget to call this method on a before_save(update) callback.

Because the changes only remains while the actual record isn't saved.

Hope it helps!


def start_date_changed?
  return true  if self.start_date != self.start_date_was 
  return false
end

I have use was which checks for the value change..

Thanx

0

精彩评论

暂无评论...
验证码 换一张
取 消