How can I check for a field only if another field has been edited in rails?

I have a table with a column called lifecycle_id, and the other is called lifecycle_change_reason. lifeycle_id is usually automatically changed by the system based on other factors, but some users have the ability to manually change the life cycle. if they do, I would like to require them to indicate the reason for the change, but I do not want to require this field at any other time. Does anyone have a suggestion on how I can perform this type of validation?

thanks:)

-C

+5
source share
2 answers

. , , - lifecycle_id_original. :

class Member < ActiveRecord::Base
  belongs_to :lifecycle

  validates :lifecycle_change_reason, :if => :lifecycle_changed?

  before_save :reset_original_lifecycle

  protected

  def lifecycle_changed?
    self.life_cycle_id != self.lifecycle_id_original && !self.lifecycle_id_original.nil?
  end

  def reset_original_lifecycle
    self.lifecycle_id_original = self.lifecycle_id
  end
end

( ) , lifecycle_change_reason , lifecycle_id . , , .

, , "" lifecycle_id, .

, . attr_accessor, , , . on_load ActiveRecord.

0

, . , , : , , - , , , - :

if params[:object_name][:life_cycle_id] != @object.life_cycle_id && params[:object_name][:life_cycle_change_reason].blank?
   flash[:error] = "You must enter a reason for changing the life cycle."
   redirect_to :back and return false # or whatever
end
-1

All Articles