Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails: How to know in advance if "save" is going to 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 it's gonna fail I don't want to execute change_some_db_values. How could I achieve this ?

like image 505
Misha Moroshko Avatar asked Dec 01 '22 03:12

Misha Moroshko


1 Answers

You can add a check for validity 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
like image 94
Skilldrick Avatar answered Dec 04 '22 06:12

Skilldrick