如何使用rails和Ajax渲染新上传的图像而无需重新加载整个页面?

时间:2015-06-18 02:37:46

标签: javascript jquery ruby-on-rails ajax

我的rails图片上传器通过模式表单将新封面照片上传到主页。我正在尝试让Ajax正常工作,这样新的图像将在不重新加载整个页面的情况下进行渲染/删除。

这是我到目前为止所拥有的:

# app/views/covers/_new_cover.html.erb

<div class="modal-body">
  ....
  <%= form_for @cover, html: {multipart: :true}, remote: true do |f| %>
      <%= f.file_field :photo %>
  ....<%= f.submit "Save", class: "btn btn-primary" %>
</div>

# app/views/covers/new_cover.js.erb

$("#modal-window").html("<%= escape_javascript(render 'covers/new_cover') %>");

控制器包含:

class CoversController < ApplicationController 
  def home
    @covers = Cover.all
    if logged_in?
      @micropost  = current_user.microposts.build
      @feed_items = current_user.feed.paginate(page: params[:page])
    end
  end

  def new
    @cover = Cover.new
  end

  def create
    @cover = Cover.new(cover_params)

    if @cover.save
      redirect_to root_path, notice: "Cover photo uploaded."
    else
      render "new"
    end
  end

  def destroy
    @cover = Cover.find(params[:id])
    @cover.destroy
    redirect_to root_path, notice:  "Cover photo deleted."
  end

  def new_cover
    @cover = Cover.new
    respond_to do |format|
      format.html
      format.js
    end
  end

private
  def cover_params
    params.require(:cover).permit(:name, :photo)
  end
end

而routes.rb文件包含:

Rails.application.routes.draw do

  get 'covers/new_cover' => 'covers#new_cover', :as => :new_cover
  get 'covers/home'
  get 'covers/new'
  get 'covers/create'
  get 'covers/destroy'

  root                'covers#home'

  resources :covers, only: [:home, :index, :new, :create, :destroy]

我在SO和Google上看过很多类似的问题,但到目前为止我无法解决它。

感谢您的帮助。

1 个答案:

答案 0 :(得分:0)

我希望在提交表单之后进行cannot match existing table structure操作,如果是,则在视图中创建create.js.erb文件并加载要显示的div create

将您的创建操作更改为

photo