开发者

combine 2 operations in if confition

开发者 https://www.devze.com 2023-01-03 22:56 出处:网络
I currently have: if @message.save @message.deliver_contact flash[:success] = t(\'Your_message_successfully_sent\')

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.

0

精彩评论

暂无评论...
验证码 换一张
取 消