【问题标题】:Updating record in model method在模型方法中更新记录
【发布时间】:2013-10-01 17:40:18
【问题描述】:

在我的 Rails 4 应用程序中,我目前正在将我的逻辑转移到我的模型中。

我的模型中的一种方法可以更改预订状态:

def withdraw
  if self.status == 1 #only allow bookings with status 1 to be updated
    self.status = 2
    GuestMailer.booking_withdrawn(self).deliver
    save!
  end
end

我从 BookingsController 调用该方法,如下所示:

if @booking.withdraw
  flash[:success] = 'The booking has been withdrawn'
end

我的问题是我是否应该在模型中使用save!,因为我只是在更新?

【问题讨论】:

    标签: ruby-on-rails model-view-controller ruby-on-rails-4


    【解决方案1】:

    您可以在此方法中使用save!。但是,可以将该方法重命名为withdraw!,以表明该方法改变了对象的状态,如果模型无法保存,则抛出异常。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-08-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多