2012-10-18 30 views
1

我书面方式使用Rails 3.2.8应用程序100%AJAX麻烦与回形针和Ajax使用Rails 3.2.8

一切都很顺利,直到我试图给员工的照片上传到员工管理模块。

这是我的代码部分:

在控制器:

class EmpleadosController < ApplicationController 
    respond_to :js 
    before_filter :require_user 

    def index 
    @empleados = Empleado.paginate(page: params[ :page ], 
            joins: [:user,:contacto], 
            select: 'empleados.id as id, empleados.user_id, empleados.contratado_el, empleados.despedido_el, empleados.nss, empleados.sueldo_base_semanal, empleados.comentarios, empleados.foto_file_name, empleados.foto_content_type, empleados.foto_file_size, empleados.foto_updated_at, users.username as username, contactos.salutacion_id as salutacion_id, contactos.id as contacto_id, contactos.nombres as nombres, contactos.apellidos as apellidos' 
           ).sorted(params[ :sort ]) 
    end 


    def new 
    @empleado = Empleado.new 
    end 

    def create 
    @empleado = Empleado.new(params[:empleado]) 
    @empleado.sueldo_base_semanal = params[:empleado][:sueldo_base_semanal].gsub(',','').gsub('$','').to_f 
    if @empleado.save 
     redirect_to empleados_path 
    else 
     render action: 'new' 
    end 
    end 
... 

现在的观点(我使用HAML):

= form_for(@empleado, remote: true, html: {multipart: true}) do |f| 
    = show_me_the_errors @empleado 

    %table.captura 
    %tr 
     %td.etiqueta 
     = f.label :user_id 
     %td.campo 
     = f.select :user_id, 
        User.usuarios_no_asignados, 
        { include_blank: true }, 
        { tabindex: 1 } 
     = image_tag 'nuevo_24.png', 
        style: 'vertical-align: bottom;', 
        id: 'empleado_nuevo_usuario' 
... (5 more text fields) ... 

    %tr 
     %td.etiqueta 
     = f.label :foto 
     %td.campo 
     = f.file_field :foto, 
         accept: 'image/png,image/gif,image/jpeg' 

事情是,虽然没有选定的文件上传,一切正常,命令respond_to :js的工作原理应该是在createindexnew之间的所有交互中。

但是,当你选择一个图像,所有交互createindexnew后成为HTML完全无视respond_to :js,我的意思是,form for行为就像如果remote: true是不存在

当一切正常那么,URL是localhost:3000并且永远不会改变,但是当我选择要上传的图片时,crete之后的URL变为localhost:3000/empleados

有没有人对此有任何线索?我一直在努力解决这个问题,最后3次失败。

Thaks提前。

回答

3

好的,经过几天试图找到问题,我开始工作的解决方法。因此,这是它:

1)我创建一个数据库表为temprary存储,与该ID字段集不自动增量,并与正常的字段名称:

mysql> describe imagens; 
+---------------------+--------------+------+-----+---------+-------+ 
| Field    | Type   | Null | Key | Default | Extra | 
+---------------------+--------------+------+-----+---------+-------+ 
| id     | int(11)  | NO | PRI | NULL |  | 
| imagen_file_name | varchar(500) | YES |  | NULL |  | 
| imagen_content_type | varchar(500) | YES |  | NULL |  | 
| imagen_file_size | int(11)  | YES |  | NULL |  | 
| imagen_updated_at | datetime  | YES |  | NULL |  | 
| created_at   | datetime  | NO |  | NULL |  | 
| updated_at   | datetime  | NO |  | NULL |  | 
| lock_version  | int(11)  | NO |  | 0  |  | 
+---------------------+--------------+------+-----+---------+-------+ 
8 rows in set (0.00 sec) 

2)在视图(_form.html.haml):

-# this variable will be used as primary key for identifying the image to upload in the database 
- ale = Time.now.to_i 

3)在视图(_form.html.haml):

我分开file_field标签

-# FORM for general data input 
= form_for(@empleado, remote: true) do |f| 
    ... 

那么,这种形式我里面添加,一个隐藏的文件与可变ale和一个漂亮的小iframe

-# I use it in order to find out for wich record to search at the temporary DBTable 
= hidden_field_tag :ale, ale 
-# this IFRAME will be used to catch the error message returned by rails when uploading the image, it will be invisible 
%iframe{src: '#', frameborder:0, height: 0, width: 0, id: 'nulo', name: 'nulo'} 

,并在其自己的form_for标签封装,但没有任何一种submitcommit按钮。

= form_for(@imagen, remote: true, html: {multipart: true, target: 'nulo'}) do |f| 
    -# used to set the primary key to this value 
    = hidden_field_tag :ale, ale 
    = f.file_field :imagen, {style: 'vertical-align: middle;'} 

那么一点点的JavaScript上传的图片,当用户选择一个,但它的由事件触发提交:

:javascript 
    $('#imagen_imagen').change(function(){ 
    $('#new_imagen').submit(); 
    }); 

4)这是模型对内容imagen可(型号/ imagen.rb):

class Imagen < ActiveRecord::Base 
    attr_accessible :imagen 
    has_attached_file :imagen, 
        styles: { t100: '100x100>', t300: '300x300X', t600: '600x600' }, 
        convert_options: { all: '-strip' }, 
        path: ":rails_root/public/system/:class/:attachment/:id/:style/:filename", 
        url: "/system/:class/:attachment/:id/:style/:filename", 
        hash_secret: 'topsecret' 
    validates_attachment_size :imagen, 
          less_than: 250.kilobytes, 
          message: (I18n.t :mensajes)[:paperclip][:grande] 
end 

5)这是在控制器中的代码/ imagens_controller.rb:

class ImagensController < ApplicationController 

    respond_to :js 
    # by the way, this sline is from authlogic, a great gem to control the access to your site 
    before_filter :require_user 

    def create 
    @imagen = Imagen.new(params[:imagen]) 
    @imagen.id = params[:ale] 
    @imagen.save 
    render text: '' 
    end 

end 

6)现在,在控制器/ empleados_controller.rb的代码是:

def create 
    @empleado = Empleado.new(params[:empleado]) 
    if @empleado.save 
    imagen = Imagen.find(params[:ale].to_i) 
    if imagen 
     @empleado.foto = imagen.imagen 
     @empleado.save 
     imagen.destroy 
    end 
    redirect_to empleados_path 
    else 
    @imagen = Imagen.new 
    render action: 'new' 
    end 
end 

7) Glosary:

imagen =图片

empleado =雇员

empleados =人员

强麦 =简称aleatorio,我的意思是,随机

照片 =图片ö摄影名

8)结论:

它的工作原理!

9)待办事项:

的缺点是,你上传图片后,它会被存储在数据库中,然后就可以取消形式或更改页面,这将离开记录和图片还活着。

在开始的时候我会在我的管理模块的链接,破坏从表中持有临时图像中的所有记录,喜欢的东西Imagen.all.each{|x| x.destroy }

稍后,我会写一个脚本,在上午2:00执行该代码。