Rails: How to check if "update_attributes" is going to fail?
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
This may not be the best answer, but it seems to answer your question.
def self.validate_before_update(buyer)#parameters AKA Buyer.validate_before_update(params[:buyer])
# creates temporary buyer which will be filled with parameters
# the temporary buyer is then check to see if valid, if valid returns fail.
temp_buyer = Buyer.new
# populate temporary buyer object with data from parameters
temp_buyer.name = buyer["name"]
# fill other required parameters with valid data
temp_buyer.description = "filler desc"
temp_buyer.id = 999999
# if the temp_buyer is not valid with the provided parameters, validation fails
if temp_buyer.valid? == false
temp_buyer.errors.full_messages.each do |msg|
logger.info msg
end
# Return false or temp_buyer.errors depending on your need.
return false
end
return true
end
The method update_attributes
returns false if object is invalid. So just use this construction
def update
if @buyer.update_attributes(param[:buyer])
my_update_database_method
else
...
end
end
If your my_update_database_method
has to be call only before update_attributes
, then you shoud use merge way, probably like this:
def update
@buyer = Buyer.find(params[:id])
@buyer.merge(params[:buyer])
if @buyer.valid?
my_update_database_method
@buyer.save
else
...
end
end