Tutorial :Dynamically set method on before_save



Question:

In my controller i want to dynamically bind my instance method to the before_save callbacks.

Is there any ways we can dynamically bind methods to the callback from controller side....

EDIT :

Controller

This original code..

def amfupdate    set_properties    validate_record  if params[:csv_header][:validate_record] == "Y" #On this condition...    super  end  

If condition is true than i want to set custom callback that will exact call after before_save but before object is saved.

I want to call this method exact after before_save.. But if condition is true on controller side ..

In Model

def validate_record    self.csv_columns.each do |csv_column|      self.errors.add_to_base(_("Invalid column name #{csv_column.column_name}.")) \        unless self.model_name.constantize.column_names.include?(csv_column.column_name)    end  end  


Solution:1

I think you're looking for something like the following. In the Model:

validate do |instance|    instance.csv_columns.each do |csv_column|      instance.errors.add :csv_columns, "Invalid column name #{csv_column.column_name}"        unless instance.class.column_names.include?(csv_column.column_name)    end  end  

This will be called before the record is saved and will abort the save if the errors are added to

UPDATE: With suggestion for conditional validations

Add an attribute to the model

attr_accessor :some_condtional  

Set this in the controller

@instance.some_conditional = true # or false  

Then the validation now looks like this:

validate do |instance|    instance.csv_columns.each do |csv_column|      instance.errors.add :csv_columns, "Invalid column name #{csv_column.column_name}"        unless instance.class.column_names.include?(csv_column.column_name)    end if instance.some_conditional  end  

Or something along those lines. In other words use the model to hold the state and communicate the logic


Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »