表单提交后使用'render'时不显示Flash消息

时间:2012-02-07 03:22:43

标签: ruby-on-rails-3 forms

在提交失败的表单后,我无法收到要显示的Flash消息。

以下是表格:

<%= form_for @question do |q| %>

  <p>
    <b>Your question</b><br />
    <%= q.text_field :title, :size => 48 %>
  </p>
  <p>
    <b>Add more details</b><br />
    <%= q.text_area :body, :size => "80x10" %>
  </p>
  <p>
    <%= q.submit %>
  </p>
<% end %>

这是处理它的控制器的一部分:

def create
    @question = current_user.questions.build(params[:question])
    if @question.save
      redirect_to questions_path, :flash => { :success => "Your question was saved!" }
    else
      flash.now[:alert => "There was a problem when trying to save your question!"]
      render 'new'
    end
  end

new操作的模板文件只包含上面的表单。

我目前正在使用此代码段(在application.html.erb中)显示Flash消息,并且在成功保存并重定向到index后适用于Flash消息:

  <% flash.each do |k, v| %>
      <div class="<%= k %>"><%= v %></div>
  <% end %>

我自己一直无法找到解决这个问题的方法,所以我希望有一双更有经验的眼睛能够省去我认为只需几分钟的启发。

谢谢!

P.S。:我还尝试过常规flash[:key => "value"]以及render 'new', :flash => {:alert => "There was a problem when trying to save your question!"}

1 个答案:

答案 0 :(得分:5)

我相信:

flash.now[:alert => "There was a problem when trying to save your question!"]

你的意思是:

 flash.now[:alert] = "There was a problem when trying to save your question!"