【问题标题】:Why isn't my flash[:alert] working?为什么我的 flash[:alert] 不工作?
【发布时间】:2015-10-04 17:07:05
【问题描述】:

在我的用户上传文件并点击“提交”后,我想提醒他们上传成功。但是当我这样做时,什么都没有发生。

这是在控制器中:

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>

谢谢!

【问题讨论】:

  • 因为你在设置flash[:alert]之前重定向(相当于return
  • 我把它们换了,还是不行?
  • 我认为redirect_to 不会返回并停止执行它之后的其余行。你图片的index.html.erb 中有flash[:alert]。图片保存成功后,您尝试在其中显示 flash[:alert] 的表单不会呈现。你应该检查你的索引文件。

标签: ruby-on-rails ruby upload alert


【解决方案1】:

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

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 应该在图片的索引页面上,即您要重定向到的页面而不是表单本身。

希望这会有所帮助。

【讨论】:

  • 谢谢!它虽然显示为页面上的文本。我想要一个弹出框的东西……有什么想法吗?再次感谢好心人~
  • 您需要一个警告框还是只需要一个框围绕它?
猜你喜欢
  • 1970-01-01
  • 2014-05-17
  • 2017-09-20
  • 2012-04-14
  • 2016-09-15
  • 2012-02-14
  • 2012-08-10
  • 2013-07-27
  • 1970-01-01
相关资源
最近更新 更多