我有一个这样的协会:
用户有很多上传上传属于用户并且有很多上传图片上传图片属于上传<--孙
在将上传添加到该用户之前,我创建了我的用户。Uploads 是 misc 类型的独立文件,但它们也可以有许多 Upload Images 链接到它们以更好地描述 Uploads(因此单独的 Upload Image 模型)。现在 Upload 和 Upload_Image 持久性发生在用户更新函数中,因为它们是嵌套的表单属性。
因为 Uploads 可以有很多 Upload_Images 我正在尝试使用 Uploadify 来保存图像,但我无法将它与其余参数哈希一起发送到用户更新函数(我曾经能够在它只是一个正在发送单个回形针图像上传)。Uploadify 现在强制我将 Upload_Image 参数发送到单独的创建操作,这应该不是问题,因为我可以简单地计算 upload_id 外键并手动分配它。
然而问题是,当我执行保存时,它会将自动生成的字段(即 id 和时间戳)保留为 nil,我该如何防止这种情况发生?
这是我的模型(简化):
用户.rb
has_many :uploads, :dependent => :destroy, :order => 'created_at desc'
accepts_nested_attributes_for :uploads, :allow_destroy => true
上传.rb
belongs_to :user
has_many :upload_images, :dependent => :destroy
accepts_nested_attributes_for :upload_images
has_attached_file :upload, :path => ":rails_root/:class/:id/:basename.:extension", :url => ":rails_root/:class /:id/:basename.:extension"
上传图片.rb
belongs_to :upload
has_attached_file :image, :styles => {:thumb => "125x125#", :small => "150x150>", :medium => "200x200>", :large => "320x240>"},
:path => ":rails_root/uploads/:upload_id/:class/:id/:style/:basename.:extension",
:url => ":rails_root/uploads/:upload_id/:class/:id/:style/:basename.:extension"
额外的
这是我的上传脚本:
<script type="text/javascript" charset="utf-8">
<%- session_key = Rails.application.config.session_options[:key] -%>
$(document).ready(function() {
// Create an empty object to store our custom script data
var uploadify_script_data = {};
// Fetch the CSRF meta tag data
var csrf_token = $('meta[name=csrf-token]').attr('content');
var csrf_param = $('meta[name=csrf-param]').attr('content');
// Now associate the data in the config, encoding the data safely
uploadify_script_data[csrf_token] = encodeURI(encodeURI(csrf_param));
// Now associate the data in the config, encoding the data safely
uploadify_script_data[csrf_token] = encodeURI(csrf_param)
$('.uploadify').uploadify(
{
uploader : '/uploadify/uploadify.swf',
cancelImg : '/uploadify/cancel.png',
multi : true,
auto : true,
script : '/uploads',
onComplete : function(event, queueID, fileObj, response, data)
{
var dat = eval('(' + response + ')');
$.getScript(dat.upload);
},
scriptData :
{
'_http_accept': 'application/javascript',
'format' : 'json',
'_method': 'post',
'<%= session_key %>' : encodeURIComponent('<%= u cookies[session_key] %>'),
'authenticity_token': encodeURIComponent('<%= u form_authenticity_token %>'),
'upload_id' : '<%= Upload.last.id + 1 %>'
}
});
$('#submit').click(function(event){
event.preventDefault();
});
$('#submit').click(function(event){
event.preventDefault();
$('.uploadify').uploadifyUpload();
});
});
</script>
和创建动作:
def create
@upload_image_test = UploadImage.new(:image => params[:Filedata])
@upload_image_test.upload_id = Upload.last.id + 1
end