使用paperclip gem添加附件

时间:2014-03-10 07:49:58

标签: ruby-on-rails ruby-on-rails-4 paperclip

我试图使用paperclip gem为我的联系人模型添加附件。看起来我可以添加附件 - 我可以选择文件没有问题。但是,当我创建联系人时,附件不会保存。我知道这是因为我可以在rails控制台中看到document_id是'nil'。

在用于创建新联系人的_form.html.erb中,我有:

<%= simple_form_for(@contact, html: {class: "form-inline well", multipart: true}, role: "form") do |f| %>
        <% if @contact.errors.any? %>
          <div id="error_explanation">
            <h2><%= pluralize(@contact.errors.count, "error") %> prohibited this contact from being saved:</h2>

            <ul>
            <% @contact.errors.full_messages.each do |msg| %>
              <li><%= msg %></li>
            <% end %>
            </ul>
          </div>
        <% end %>

        <div class="form-group">

          <%= f.input :name %>
          <%= f.input :category %>
          <%= f.input :area %>
          <%= f.input :phone %>
          <%= f.input :website %>
          <%= f.input :email %>

          <%= f.fields_for :document do |document_fields| %>
            <%= document_fields.input :attachment, as: :file %>
          <% end %>

          <%= f.button :submit, class: "btn-success" %>
        </div>
      <% end %>

我的数据库迁移是:

class CreateDocuments < ActiveRecord::Migration
  def change
    create_table :documents do |t|

        t.integer :user_id
        t.timestamps
    end

    add_index :documents, :user_id
    add_attachment :documents, :add_attachment
    add_column :contacts, :document_id, :integer
  end
end

我的document.rb模型是:

class Document < ActiveRecord::Base

    has_attached_file :attachment, :styles => { :medium => "300x300>", :thumb => "100x100>" }, :default_url => "/images/:style/missing.png"
    validates_attachment_content_type :attachment, :content_type => /\Aimage\/.*\Z/
end

和contact.rb是:

class Contact < ActiveRecord::Base
    belongs_to :user
    belongs_to :document

    accepts_nested_attributes_for :document

    validates :name, presence: true,
                        length: { minimum: 2}

    validates :user_id, presence: true
end

我在contacts_controller.rb中的行为是:

    def create
    @contact = current_user.contacts.new(contact_params)

    respond_to do |format|
      if @contact.save
        format.html { redirect_to @contact, notice: 'Contact was successfully created.' }
        format.json { render action: 'show', status: :created, location: @contact }
      else
        format.html { render action: 'new' }
        format.json { render json: @contact.errors, status: :unprocessable_entity }
      end
    end
  end
  def contact_params
    params.require(:contact).permit(:name, :email, :category, :area, :organisation, :website, :phone, :user_id, document_attributes: [:id, :attachment])
   end

  # PATCH/PUT /contacts/1
  # PATCH/PUT /contacts/1.json
  def update

    @contact = current_user.contacts.find(params[:id])
    if params[:contact] && params[:contact].has_key?(:user_id)
      params[:contact].delete(:user_id) 
    end
    respond_to do |format|
      if @contact.update((contact_params))
        format.html { redirect_to @contact, notice: 'Contact was successfully updated.' }
        format.json { head :no_content }
      else
        format.html { render action: 'edit' }
        format.json { render json: @contact.errors, status: :unprocessable_entity }
      end
    end

  end

当我尝试使用附件创建新联系人时,这是我的heroku日志:

  

2014-03-10T23:41:49.594786 + 00:00 app [web.1]:参数:   { “UTF8”=&gt; “中✓”,   “authenticity_token”=&gt; “中FGitLGkHzfw15yksCusGDvwdb // CgMyOMFh4SS4l63Y =”,   “contact”=&gt; {“name”=&gt;“Oliver OT”,“category”=&gt;“OT”,“area”=&gt;“Rockdale”,   “phone”=&gt;“”,“网站”=&gt;“”,“电子邮件”=&gt;“”,   “document_attributes”=&GT; { “附件”=&GT;#,   @ original_filename =“Screen Shot 2014-03-03 at 9.24.40 pm.png”,   @ content_type =“image / png”,@ headers =“Content-Disposition:form-data;   名= \ “接触[document_attributes] [附件] \”;文件名= \“屏幕   拍摄2014-03-03 at 9.24.40 pm.png \“\ r \ nConContent-Type:   image / png \ r \ n“&gt;}},”commit“=&gt;”创建联系人“}   2014-03-10T23:41:49.594786 + 00:00 app [web.1]:参数:   { “UTF8”=&gt; “中✓”,   “authenticity_token”=&gt; “中FGitLGkHzfw15yksCusGDvwdb // CgMyOMFh4SS4l63Y =”,   “contact”=&gt; {“name”=&gt;“Oliver OT”,“category”=&gt;“OT”,“area”=&gt;“Rockdale”,   “phone”=&gt;“”,“网站”=&gt;“”,“电子邮件”=&gt;“”,   “document_attributes”=&GT; { “附件”=&GT;#,   @ original_filename =“Screen Shot 2014-03-03 at 9.24.40 pm.png”,   @ content_type =“image / png”,@ headers =“Content-Disposition:form-data;   名= \ “接触[document_attributes] [附件] \”;文件名= \“屏幕   拍摄2014-03-03 at 9.24.40 pm.png \“\ r \ nConContent-Type:   image / png \ r \ n“&gt;}},”commit“=&gt;”创建联系人“}

我不确定如何正确保存附件?

2 个答案:

答案 0 :(得分:0)

contact_params方法移到更新操作之外,以便create操作可以访问它并将其更改为以下代码。

def contact_params
  params.require(:contact).permit(:name, :email, :category, :area, :organisation, :website, :phone, :user_id, document_attributes: [:id, :attachment])
end

上面的代码允许id的{​​{1}}和attachment参数。

答案 1 :(得分:0)

您的迁移存在问题:

add_attachment :documents, :add_attachment

这意味着您的数据库表的附件列将改为add_attachment,从而导致Paperclip无法正常工作

您需要使用以下迁移更改数据库中的列:

class Migration < ActiveRecord::Migration
  def change
    rename_column :documents, :add_attachment_file_name, :attachment_file_name
    rename_column :documents, :add_attachment_content_type, :attachment_content_type
    rename_column :documents, :add_attachment_file_size, :attachment_file_size
    rename_column :documents, :add_attachment_updated_at, :attachment_updated_at
  end
end