Rails中图像上传的Flash通知

时间:2014-10-21 13:49:06

标签: ruby-on-rails ruby jquery-fileupload-rails

我正在使用jQuery File Upload gem上传文件。

我想在文件上传时显示闪光通知,但是当我上传图像时没有任何反应。

我是通过Ajax这样做的。恢复,删除和存档等所有其他操作都正常。 以下是我的控制器操作:

def upload
    set_access_control_headers
    @picture = Picture.new(picture_params)
    if params[:picture][:file]
      @picture.update_attributes({
          file: params[:picture][:file],
      })
    end
    flash[:notice] = "Picture is uploaded sucessfully!"
    @frame = @picture.frame
    @pictures = @frame.pictures.non_archived_pictures.paginate(:page => params[:page], :per_page => 12)
    @frame.notify_add(@picture.file_url, @picture.message)
    render json: {files: @frame.pictures.collect{|pic| pic.to_jq_upload}}
  end

这是upload.js.erb文件:

$("#non_archived_pictures").replaceWith('<div id=non_archived_pictures><%= j render :partial=>"frames/current_pictures" %></div>');
$(".page-wrapper').after('<%= j render :partial=>"frames/picture_modal",:locals=>{:picture=>@picture} %>")
$(".custom-header").after("<div class='alert alert-success' role=alert><%= flash[:notice] %></div>")
$(".alert-success").remove()

1 个答案:

答案 0 :(得分:0)

由于这是一个Ajax请求,因此当前请求中的客户端无法自动使用flash。您可以将通知作为要返回的JSON对象的一部分传递。

 render json: {files: @frame.pictures.collect{|pic| pic.to_jq_upload}, notice: "Picture is uploaded sucessfully!"}

在JavaScript文件中,您可以使用传递的notice密钥访问邮件。

如果您希望呈现js,还需要将回复呈现为json而不是upload.erb.js

<强>更新

flash提供了一种在操作之间传递临时对象的方法。您放入闪存中的任何内容都只会暴露给下一个操作,然后清除。例如:

def creat
  flash[:notice] = "Post successfully created"
  redirect_to @post
end

在上面的示例中,一旦通过redirect_to调用向服务器发送新请求,视图就可以使用flash

更新2

使用flash.now访问当前请求中的Flash内容:

flash.now[:notice] = "Picture is uploaded sucessfully!"