Rails: how do you know in advance if save will fail?

Consider this code of my controller:

def create change_some_db_values buyer = Buyer.new(params[:buyer]) if buyer.save redirect_to(:action => 'index') else render('new') end end 

I would like to know in advance if buyer.save will fail or not. If this happens, I do not want to perform change_some_db_values . How could I achieve this?

+4
source share
3 answers

You can add a check to save before saving :

 def create buyer = Buyer.new(params[:buyer]) if buyer.valid? change_some_db_values end if buyer.save redirect_to(:action => 'index') else render('new') end end 
+10
source

It is best to include all changes in the transaction , and then rollback if save fails.

 def create Buyer.transaction do change_some_db_values buyer = Buyer.new(params[:buyer]) buyer.save! end end 
+7
source

Can you use valid? function valid? to find out if the object is valid for operations. Here is an example of code that implements this approach:

 def create # change_some_db_values buyer = Buyer.new(params[:buyer]) if buyer.valid? change_some_db_values end if buyer.save redirect_to(:action => 'index') else render('new') end end 
+1
source

Source: https://habr.com/ru/post/1335651/


All Articles