_changed?在rails 3.1.0 app中没有用

时间:2012-02-09 20:12:36

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

以下是发票控制器中的更新代码:

  def update
      @invoice = Invoice.find(params[:id])
      if @invoice.approved_by_corp_head_changed?
        @invoice.approve_date_corp_head = Time.now
        @invoice.corp_head_id = session[:user_id]
      end
      if @invoice.update_attributes(params[:invoice], :as => :roles_update)
        redirect_to URI.escape("/view_handler?index=0&msg=Updated")
      else
        flash.now[:error] = 'Not saved!'
        render 'edit'
      end
  end

approved_by_corp_head的值已正确保存。问题是if @invoice.approved_by_corp_head_changed?始终为false并且IF循环永远不会被执行。在rails控制台中,@ invoice.approved_by_corp_head_changed?如果值已更改,则为true。这可能有什么问题?非常感谢。

1 个答案:

答案 0 :(得分:3)

因为您直接从数据库中获取对象,所以它是全新的,所以没有理由以某种方式对其进行更改。

此外,_changed?可用,直到实际保存对象。

一种选择是从params获取更改,但不直接更新您的对象。这个问题has been discussed here

旁注:你为什么这样做:

redirect_to URI.escape("/view_handler?index=0&msg=Updated")

而不是:

redirect_to path_name_path(:index => 0, :msg => "Updated")