Rails 3 - 如何在更新保存之前更改控制器中的属性?

rya*_*ts1 0 controller ruby-on-rails

所以,我有更新数据库中记录的表单。在我的控制器update操作中,如果另一个值是Estimate. 也许这会更有意义......这就是我想要做的。

def update
    @invoice = Invoice.find(params[:id])
    if @invoice.update_attributes(params[:invoice])
        if@invoice.status == "Estimate"
            # if the value of status is Estimate then change the
            # value of estimate_sent_date to the current timestamp
        end
        redirect_to invoices_path
    else
        render 'edit'
    end
end
Run Code Online (Sandbox Code Playgroud)

我所关心的表单的唯一值是statusand estimate_sent_date。大多数情况下,我只是不确定如何更改estimate_sent_date和保存该记录的值。

另外,我应该保存所有内容,然后单独调用以保存estimate_sent_date还是一次性保存所有内容?我想我可以estimate_sent_date在调用之前更改 的值if @invoice.update_attributes(params[:invoice]),不是吗?

谢谢您的帮助!

agu*_*ren 5

正如 Ryan Bigg 所说,状态机在这里确实有效。另一种解决方案是before_save在 Invoice 模型上使用回调,如下所示:

before_save :set_sent_date

def set_sent_date
  if self.status_changed? && self.status == "Estimate"
     self.estimate_sent_date = Time.now
  end
end
Run Code Online (Sandbox Code Playgroud)