为什么我的 flash[:alert] 不工作?

Why isn't my flash[:alert] working?

在我的用户上传文件并点击 "submit" 后,我想提醒他们上传成功。但是当我这样做时没有任何反应。

这里是在控制器中:

def create
    # make a new picture with what picture_params returns (which is a method we're calling)
    @picture = Picture.new(picture_params)
    if @picture.save
      # if the save for the picture was successful, go to index.html.erb
      redirect_to pictures_url
      flash[:alert] = "Upload successful!"
    else
      # otherwise render the view associated with the action :new (i.e. new.html.erb)
      render :new
    end
  end

表格:

<container>
<center>
<%= form_for @picture do |f| %>
  <input type="file" multiple>  <%= f.file_field :picture %>
  <p>Drag your files here or click in this area.</p>
  <button type="submit"> <%= f.submit "Save" %> Upload </button>
  <% if flash[:alert] %>
    <div class="alert"><%= flash[:alert] %></div>
  <% end %>
</form>
<% end %>
</container>

谢谢!

你的创建方法应该是这样的:

def create
    @picture = Picture.new(picture_params)
    if @picture.save
      flash[:alert] = "Upload successful!"
      redirect_to pictures_url
    else
      render :new
    end
  end

重定向应该在 flash 之后。你也可以这样做:

redirect_to pictures_url, alert: "Upload successful!"

并且您为 Flash 消息创建的 div 应该在图片的索引页上,即您要重定向到的页面而不是表单本身。

希望对您有所帮助。