0

我的视图中有一个链接,它通过 ajax 调用下面的方法。我基本上是在尝试获取通过 插入的记录的 id @application.update_attributes(params[:application]),但是当我调用时@curr_app = @application.application_field.last,它返回在我的 ajax 调用之前插入的最后一条记录。

例如,如果我最初点击页面并说 application_fields 表中的最高 id 是 50,那么当我点击我的 ajax 链接时,@curr_app.id无论我点击我的 ajax 链接多少次,它始终是 50。

我想@application.application_field.last应该得到数据库中的最后一条记录?如何获取最后插入的记录?我必须重新查询吗?

  # PUT /applications/1
  # PUT /applications/1.json
  def update
    @application = Application.find(params[:id])

    respond_to do |format|
      if @application.update_attributes(params[:application])

        @curr_app = @application.application_field.last
        puts @curr_app.id

        format.html { redirect_to @application, notice: 'Application was successfully updated.' }
        format.json { head :no_content }
        format.js
      else
        format.html { render action: "edit" }
        format.json { render json: @application.errors, status: :unprocessable_entity }
        format.js
      end
    end
  end
4

4 回答 4

0

我最终不得不重新查询数据库以获取最后一条记录。

于 2013-01-03T20:16:08.267 回答
0

你有没有尝试过:

@app = Application.find(:last)
于 2013-03-27T14:03:33.637 回答
0

我相信你必须做

@application.reload

但是,Rails 在同一请求处理期间缓存查询,因此它可能会从缓存中获取结果,而不是从数据库中获取结果。您只需要尝试查看日志即可查看它的来源。

或者可能

@curr_app = ApplicationField.last
于 2012-12-07T21:25:21.730 回答
0

您可以用来获取 id 的相同变量是:@curr_id = @application.id 在您离开此页面之前,它仍然具有带有数据的 json。

def update
@application = Application.find(params[:id])

respond_to do |format|
  if @application.update_attributes(params[:application])

    @curr_app = @application.id

    format.html { redirect_to @application, notice: 'Application was successfully updated.' }
    format.json { head :no_content }
    format.js
  else
    format.html { render action: "edit" }
    format.json { render json: @application.errors, status: :unprocessable_entity }
    format.js
  end
end

结尾

于 2017-04-24T22:33:42.003 回答