原因是:在Rails 3中重定向后没有显示通知

mav*_*air 9 ruby-on-rails-3

我的控制器中有以下代码

  def create
    @tv_show = TvShow.new(params[:tv_show])

    respond_to do |format|
      if @tv_show.save
        format.html { redirect_to(tv_shows_path, :notice => 'Tv show was successfully created.') }
        format.xml  { render :xml => @tv_show, :status => :created, :location => @tv_show }
      else
        format.html { render :action => "new" }
        format.xml  { render :xml => @tv_show.errors, :status => :unprocessable_entity }
      end
    end
  end
Run Code Online (Sandbox Code Playgroud)

以及我的tv_shows/index.html.erb中的以下内容

<div id="notice"><%= notice %></div>
Run Code Online (Sandbox Code Playgroud)

但是当我创建一个新条目时,重定向到tv_shows_path后才会出现通知消息.谁知道为什么?

Sha*_*aun 17

你有什么理由想要使用:notice而不是flash[:notice]吗?

控制器:

 respond_to do |format|
  if @tv_show.save
    format.html { 
      flash[:notice] = 'Tv show was successfully created.'
      redirect_to tv_shows_path 
    }
    format.xml  { render :xml => @tv_show, :status => :created, :location => @tv_show }
  else
    format.html { render :action => "new" }
    format.xml  { render :xml => @tv_show.errors, :status => :unprocessable_entity }
  end
end
Run Code Online (Sandbox Code Playgroud)

视图:

<% if flash[:notice] %>
    <div id="notice"><%= flash[:notice] %></div>
<% end %>
Run Code Online (Sandbox Code Playgroud)

  • 在Rails 3的`redirect_to`中接受`:notice`和`:alert`. (11认同)

mav*_*air 0

代码不起作用的原因是我的身份验证代码有问题...在我从头开始实现新的身份验证方式后,上面的代码就可以工作了。

  • 我想知道你是否可以具体一点。我遇到了完全相同的问题,这个答案没有帮助。我的控制器有“before_filter:authenticate_user!”。这是错误的吗? (3认同)