Rails:如何提前知道“保存”是否会失败?

时间:2011-01-15 11:50:40

标签: ruby-on-rails ruby-on-rails-3

考虑我的控制器的这段代码:

def create
  change_some_db_values
  buyer = Buyer.new(params[:buyer])
  if buyer.save
    redirect_to(:action => 'index')
  else
    render('new')
  end
end

我想提前知道buyer.save是否会失败。如果它会失败,我不想执行change_some_db_values。我怎么能做到这一点?

3 个答案:

答案 0 :(得分:11)

你可以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

答案 1 :(得分:7)

更好的方法可能是将所有更改放入transaction,然后在save失败时回滚。

def create
  Buyer.transaction do
    change_some_db_values
    buyer = Buyer.new(params[:buyer])
    buyer.save!
  end
end

答案 2 :(得分:1)

您可以使用valid?函数查看对象是否对操作有效。以下是实现此方法的示例代码:

def create
  # change_some_db_values
  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