在Rails 3应用程序的控制器中,我正在尝试测试字段是否更改,然后在重定向页面上刷新消息。
这是我正在尝试的代码:
class CostprojectsController < ApplicationController
def update
@costproject = Costproject.find(params[:id])
@costquestion = @costproject.costquestion
nextpath = edit_costquestion_path(@costquestion) if params[:tab1]
nextpath = costprojects_editcostestimates_path(:id => @costproject.id) if params[:tab2]
nextpath = costprojects_editattachments_path(:id => @costproject.id) if params[:tab3]
if nextpath == nil
if User.current.admin?
nextpath = costprojects_path
else
nextpath = clients_costcurrent_path
end
end
flash[:success] = "Project Submitted" if @costproject.submit_date_changed?
respond_to do |format|
if @costproject.update_attributes(params[:costproject])
format.html { redirect_to nextpath }
format.json { render json: @costproject }
else
format.html { render action: "edit" }
format.json { render json: @costproject.errors, status: :unprocessable_entity }
end
end
end
这条线不起作用:
flash[:success] = "Project Submitted" if @costproject.submit_date_changed?
@ costproject.submit_date是一个有效字段 - 它在测试期间得到更新。
答案 0 :(得分:1)
你正在更新你的@costproject if if条件,我想你应该在之前做。
只有在update_attributes返回true时才应考虑这样做,如下面的代码所示:
respond_to do |format|
if @costproject.update_attributes(params[:costproject])
flash[:success] = "Project Submitted" if @costproject.previous_changes.include?(:submit_date)
format.html { redirect_to nextpath }
format.json { render json: @costproject }
else
format.html { render action: "edit" }
format.json { render json: @costproject.errors, status: :unprocessable_entity }
end
end