通过输入上传完成后Rails4然后如何触发bootstrap模式?

我的Gemfile:

gem 'rails', '4.2.8' gem 'carrierwave', '~> 1.2', '>= 1.2.2' gem 'mini_magick', '~> 4.8' gem 'Jcrop', '~> 0.1.0' 

现在我想使用form_for上传用户图片,我的show.html.erb

   {:multipart => true} do |f| %> 
@user.name+"_avatar" %> @user.name+"_default" %>

我的user_controller.rb

 def update @user = User.find(params[:id]) if @user.update_attributes(user_params) if params[:user][:picture].present? respond_to do |format| format.html do flash[:warning] = "Template missing" redirect_to @user end format.js { render template: 'users/update.js.erb'} end else redirect_to @user flash[:success] = "Success update" end else render :edit end end 

我的update.js.erb

 $('#uploadModalContent').html(""); $('#upload-modal').modal('show'); 

我的_modal.html.erb

  

现在我需要上传图片后, _modal.html.erb可以显示。 但似乎format.js { render template: 'users/update.js.erb'} user_controller.rb正常工作。 这是为什么?

我应该在user_controller.rb中做什么, input完成onchange: 'this.form.submit()'它可以渲染到模态窗口? 非常感谢你的帮助。

我找到了另一种在rails中上传图像的方法。 我到达了conclusio,这是迄今为止我所知道的最好的方法。 你必须使用carrierwave gem。 我现在将把所需的代码用于使用它。 无论如何,如果你可以检查github回购或这篇文章 。

好吧,让我们走吧。 您将首先在全局安装gem,但即使在本地项目中也是如此。

 $ gem install carrierwave 

在Rails中,将其添加到您的Gemfile:

 gem 'carrierwave', '~> 1.0' 

现在重新启动服务器以应用更改。

首先生成一个上传器:

 rails generate uploader Photos 

这应该给你一个文件:

 # app/uploaders/photos_uploader.rb class PhotosUploader < CarrierWave::Uploader::Base storage :file # will save photos in /app/public/uploads def store_dir "uploads/#{model.class.to_s.underscore}/#{mounted_as}/#{model.id}" end end 

创建照片迁移

 class CreatePhotos < ActiveRecord::Migration def change create_table :photos do |t| t.string :name, :null => false t.binary :data, :null => false t.string :filename t.string :mime_type t.timestamps null: false end end end 

和模型

 require 'carrierwave/orm/activerecord' class Photo < ActiveRecord::Base mount_uploader :data, PhotosUploader end 

然后控制器

 class PhotosController < ApplicationController def index @photos = Photo.all end def show @photo = Photo.find(params[:id]) end def new @photo = Photo.new end def create # build a photo and pass it into a block to set other attributes @photo = Photo.new(photo_params) # normal save if @photo.save redirect_to(@photo, :notice => 'Photo was successfully created.') else render :action => "new" end end private def photo_params params.require(:photo).permit! end end 

表格上传:

  <%= form_for(@photo, :html => {:multipart => true}) do |f| %> 
<%= f.label :name %> <%= f.text_field :name %>
<%= f.label :data %> <%= f.file_field :data %>
<%= f.submit "Upload" %>
<% end %>

然后在这样的视图中加载文件。

  

Photo: <%= @photo.name %>

<%= image_tag @photo.data.url %>

您还可以在图片上传后触发模态,如下所示:

 # app/assets/javascripts/photos.coffee $ -> alert('Photo Uploaded - You can launch modal here') 

好吧就是这样。 让我知道怎么回事!