larryzhao
larryzhao

Reputation: 3213

how to use Paperclip alone with a separated attachment model

I have a scenario that my user need to upload a image first and then assign to another model, so I used a generic model, to upload the file first,

model:

class AttachedImage < ActiveRecord::Base
  belongs_to :attachable, :polymorphic => true

  has_attached_file :image
end

migration:

class CreateAttachedImages < ActiveRecord::Migration
  def change
    create_table :attached_images do |t|

      t.string      :image_file_name
      t.string      :image_content_type
      t.integer     :image_file_size
      t.datetime    :image_updated_at
      t.references  :attachable,  :polymorphic => true

      t.timestamps
    end
  end
end

And the view and the controller are like the following:

class AttachedImagesController < ApplicationController
  def create

    @attched_image = AttachedImage.new(params)

    respond_to do |format|  
      if @attched_image.save  
        format.js  
      else
        format.js  
      end  
    end
  end
end

the view part:

<div id="upload-image-dialog">
    <%= form_tag(@attached_image, :method => "POST", :remote => true, :html => { :multipart => true }) do %>
      <%= file_field_tag :image %>
      <%= submit_tag("submit") %>
    <% end %>
    <h1 style="display:none">Successfully Uploaded.</h1>
</div>

it's quite straight forward, but every time I submit this form, I will get an exception of the utf8 field added automatically by rails. I could not understand that, this shall not be a problem right? We are writing @model = Model.new(params) everyday, hope someone could help me out and explain what's going on under the hood, thanks!

ActiveRecord::UnknownAttributeError (unknown attribute: utf8):
  app/controllers/attached_images_controller.rb:5:in `new'
  app/controllers/attached_images_controller.rb:5:in `create'

Upvotes: 0

Views: 541

Answers (1)

rubyprince
rubyprince

Reputation: 17793

Problem is here:

@attched_image = AttachedImage.new(params)

You are passing all the params to save(that is why you are getting utf8 error, it is inside params). It should be:

@attched_image = AttachedImage.new(params[:attached_image])

Upvotes: 1

Related Questions