【问题标题】:_changed? in rails 3.1.0 app did not work_改变了吗?在 rails 3.1.0 应用程序不起作用
【发布时间】:2012-03-02 08:19:00
【问题描述】:

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

  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? 总是假的,IF 循环永远不会被执行。在 Rails 控制台中,@invoice.approved_by_corp_head_changed?如果值改变,则为真。这里有什么问题?非常感谢。

【问题讨论】:

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


    【解决方案1】:

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

    此外,_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")
    

    【讨论】:

    • 谢谢。我想知道在调用 update_attributes 之前是否更改了 @invoice。 view_handler 是保留查看历史记录的自定义方法。 Back in rails 会在编辑或创建后形成一个循环。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-06-09
    • 2014-01-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多