user938363
user938363

Reputation: 10378

_changed? in rails 3.1.0 app did not work

Here is the code for update in invoice controller:

  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

Value of approved_by_corp_head was saved correctly. The problem is that if @invoice.approved_by_corp_head_changed? was always false and the IF loop never gets executed. In rails console, the @invoice.approved_by_corp_head_changed? is true if the value is changed. What could be wrong here? Thanks so much.

Upvotes: 0

Views: 95

Answers (1)

apneadiving
apneadiving

Reputation: 115541

Because you fetch an object directly from the database, it's brand new, so there is no reason it could be changed somehow.

Moreover, _changed? is available until the object is actually saved.

One option would be to get the changes from the params but not update your object directly. This issue has been discussed here.

Sidenote: why do you do:

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

instead of:

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

Upvotes: 3

Related Questions