TK-*_*421 6 ruby-on-rails paperclip ruby-on-rails-3
有没有人有多个附件的Rails 3示例在多部分表单上进行验证?我一直在努力让这个工作永远工作(并且我已经找到了每一篇博文和消息,但没有一个能够涵盖这种情况,而且文档根本没有帮助).
第一个问题是大多数例子都使用'new_record?' 在视图模板中,但是当验证失败时,它总是在new/create序列中返回true,因为没有保存模型实例(因此没有'id'值).因此,如果您从5个模型实例/文件输入开始并上传一个文件,则在重新呈现新视图时,您现在有6个文件输入,并且'unless'子句因同样的原因而失败,并且没有显示缩略图.
我想保留上传文件的链接(我知道这是可能的 - 他们生活在临时目录中),同时向用户提供其他必填字段的验证错误.
有人在某处必须使用Paperclip.;)
您可以通过使用三个模型和一些控制器魔法来实现这一目标。
第一个模型是您真正想要的模型。就说传记吧。
class Biography < ActiveRecord::Base
has_one :biography_fields
has_many :biography_attachments
end
class BiographyFields < ActiveRecord::Base
belongs_to :biography
# Validations
end
class BiographyAttachment < ActiveRecord::Base
belongs_to :biography
# Paperclip stuff
end
Run Code Online (Sandbox Code Playgroud)
现在在你的控制器中你可以做这样的事情:
class BiographiesController
def some_method
@biography = Biography.find(params[:biography_id]) || Biography.create!
if @biography.biography_data.create(params[:biography_data])
# Try to save the uploads, if it all works, redirect.
else
# Still try the uploads, if they work, save them and make sure to pass the :biography_id as a hidden field so they can be used without re-uploading. Also reflect this in the form.
end
end
end
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
4645 次 |
最近记录: |