我有一个场景,我的用户需要首先上传图像,然后分配给另一个模型,所以我使用通用模型,首先上传文件,
模型:
class AttachedImage < ActiveRecord::Base
belongs_to :attachable, :polymorphic => true
has_attached_file :image
end
迁移:
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
视图和控制器如下所示:
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
视图部分:
<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>
它很直接,但每次提交此表单时,我都会得到一个由rails自动添加的utf8字段的例外。我无法理解,这不应该是一个问题吧?我们每天都在写@model = Model.new(params),希望有人可以帮我解释一下发生了什么,谢谢!
ActiveRecord::UnknownAttributeError (unknown attribute: utf8):
app/controllers/attached_images_controller.rb:5:in `new'
app/controllers/attached_images_controller.rb:5:in `create'
答案 0 :(得分:1)
问题出在这里:
@attched_image = AttachedImage.new(params)
你传递所有的参数来保存(这就是为什么你得到utf8错误,它在params内)。它应该是:
@attched_image = AttachedImage.new(params[:attached_image])