为什么我的闪光灯[:提醒]无法正常工作?

时间:2015-07-15 15:05:16

标签: ruby-on-rails ruby upload alert

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

这是在控制器中:

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>

谢谢!

1 个答案:

答案 0 :(得分:1)

您的创建方法应如下所示:

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

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

redirect_to pictures_url, alert: "Upload successful!"

您为flash消息创建的div应位于图片的索引页面上,即您要重定向到的页面,而不是表单本身。

希望这有帮助。