combine 2 operations in if confition
I currently have:
if @message.save
@message.deliver_contact
flash[:success] = t('Your_message_successfully_sent')
redirect_to root_url
else
render :action => 'new'
end
In this code a message is first saved in the database and afterwards sent out (@message.deliver_contact). But, if the delivering fails, the record was already written away.
I want to reach that: * I only give the success flash if BOTH operations succeed (saving and sending) * if ONE operation fails, none of the operations should be execu开发者_运维百科ted (or the save should be rolled back).
I'm not experienced, anybody an idea how I should write that?
I think you may be looking for the and operator &&
. 'If both the operands are non zero then then condition becomes true.' - source. It allows you to say:
if (a == true) && (b == true)
-# only runs if both a AND b are true
To apply this to your example would be:
if @message.save && @message.deliver_contact
flash[:success] = t('Your_message_successfully_sent')
redirect_to root_url
else
render :action => 'new'
end
Following up from the comments regarding transactions, you might be wanting something along the lines of:
@message.transaction do
@message.save
@message.deliver_contact
rescue ActiveRecord::StatementInvalid
render :action => 'new'
end
end
See the "Exception handling and rolling back" section from The Rails API - ActiveRecord::Transactions::ClassMethods. You may need to play around.
精彩评论