Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use After_save with condition?

I'm unable to find that on google. I have 3 models.

model 1 -> has_many model 2 -> has many model 3

model 1 has fields to determine how many model 2 are possible to create. and model 2 has fields to know how many model 3 must be created.

I would like when i save model 1, create automatically model 2 and model 3.

i thinked to use from model 1 after_create create_model2_record

def create_model2_record
  for(x=0, x<=model1.field; x++){  #c sample
    @model2 = Model2.new
  }
end 

how can handle this with rails 3? thansk

like image 801
neimad Avatar asked Sep 08 '25 12:09

neimad


1 Answers

class Model1 << ....
  after_save :create_related_models, :if => :some_condn? #use the condition only if needed

  def create_related_models
    @model2 = Model2.new
    @model2... = ...  #assign values to Model2 variables
    if @model2.save
      @model3 = Model3.new
      @model3... = ...  #assign values to Model3 variables
      @model3.save
    end
  end
  ...
end

Well, this is a basic idea of how it can be done. You can change the code inside create_related_models as you wish, and also choose to use or not to use the condition in after_save. One scenario to use the condition might be a case when need to decide whether to create Model2 and Model3 based on the value of a certain variable in Model1. I hope this works for you. Thanks.

like image 149
rookieRailer Avatar answered Sep 11 '25 01:09

rookieRailer