Rails: How to check if "update_attributes" is going to fail?

Misha Moroshko picture Misha Moroshko · Jan 17, 2011 · Viewed 12.6k times · Source

To check if buyer.save is going to fail I use buyer.valid?:

def create
  @buyer = Buyer.new(params[:buyer])
  if @buyer.valid?
    my_update_database_method
    @buyer.save
  else
    ...
  end
end

How could I check if update_attributes is going to fail ?

def update 
  @buyer = Buyer.find(params[:id])
  if <what should be here?>
    my_update_database_method
    @buyer.update_attributes(params[:buyer])
  else
    ...
  end
end

Answer

EnabrenTane picture EnabrenTane · Jan 17, 2011

it returns false if it was not done, same with save. save! will throw exceptions if you like that better. I'm not sure if there is update_attributes!, but it would be logical.

just do

if @foo.update_attributes(params)
  # life is good
else
  # something is wrong
end

http://apidock.com/rails/ActiveRecord/Base/update_attributes

Edit

Then you want this method you have to write. If you want to pre check params sanitation.

def params_are_sanitary?
  # return true if and only if all our checks are met
  # else return false
end

Edit 2

Alternatively, depending on your constraints

if Foo.new(params).valid? # Only works on Creates, not Updates
  @foo.update_attributes(params)
else
  # it won't be valid.
end