重定向或渲染后不显示 Flash 消息

2024-03-01

使用 Rails 4 和 ruby​​ 2

无法显示来自我的控制器的闪烁消息。我的方法如下所示:

def create
    @salary_report = SalaryReport.create(salary_report_params)
    if @salary_report.save  
      redirect_to @salary_report
      flash[:notice] = "Lönerapporten sparades korrekt!"
      puts "salary report saved #{flash[:notice]}"
    else
      render :new, notice: "Något gick fel när lönerapporten skulle sparas!"      
    end
  end

正如您所看到的,我添加了一条 put 语句,打印出 flash 通知,只是为了证明 flash 通知是在重定向后生成的。

创建工资报告后,日志如下所示:

Redirected to http://localhost:3000/salary_reports/20
salary report saved Lönerapporten sparades korrekt!
Completed 302 Found in 25ms (ActiveRecord: 9.7ms)

获取显示查看日志后:

Started GET "/salary_reports/22" for 127.0.0.1 at 2013-07-24 16:08:42 +0200
Processing by SalaryReportController#show as HTML
  Parameters: {"id"=>"22"}
  SalaryReport Load (0.5ms)  SELECT "salary_reports".* FROM "salary_reports" WHERE         "salary_reports"."id" = ? LIMIT 1  [["id", "22"]]
  Document Lo ad (0.3ms)  SELECT "documents".* FROM "documents" WHERE          "documents"."salary_report_id" = ?  [["salary_report_id", 22]]
  Rendered salary_report/show.html.erb within layouts/application (6.1ms)
  User Load (0.3ms)  SELECT "users".* FROM "users" WHERE "users"."id" = 3 ORDER BY     "users"."id" ASC LIMIT 1
Completed 200 OK in 62ms (Views: 58.0ms | ActiveRecord: 1.1ms)

在视图中,我用以下方式显示消息:

<% flash.each do |name, msg| %>
      <% if msg.is_a?(String) %>
        <div class="alert alert-<%= name == :notice ? "success" : "error" %>">
          <a class="close" data-dismiss="alert">&#215;</a>
          <%= content_tag :div, msg, :id => "flash_#{name}" %>
        </div>
      <% end %>
    <% end %>

我尝试了多种不同的方法来编写控制器方法,但似乎没有任何帮助。非常不确定问题可能是什么。


您正在设置您的flash[:notice]重定向后。尝试切换这些调用的顺序,即首先设置 Flash 消息,然后设置重定向:

def create
    @salary_report = SalaryReport.create(salary_report_params)
    if @salary_report.save  
      flash[:notice] = "Lönerapporten sparades korrekt!"
      puts "salary report saved #{flash[:notice]}"
      redirect_to @salary_report
    else
      render :new, notice: "Något gick fel när lönerapporten skulle sparas!"      
    end
  end
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

重定向或渲染后不显示 Flash 消息 的相关文章

随机推荐