我有一篇文章表单列出文章,包括一个表单,用于提交带有嵌套字段的新文章,用于附加照片。
表格可以保存文章和照片。
当验证失败时,我只需渲染索引操作即可正确显示验证错误。
当我渲染索引操作时,错误的表单数据会正确显示,但是不会保留所选的照片,因此用户必须更正其数据输入,然后重新连接照片。
这是一个问题,因为用户倾向于更正表单数据然后提交,而不会注意到他们的照片没有附加。
def index
@article = Article.new
@articles = Article.all
end
def create
@article = Article.new(discussion_params)
@article.user_id = current_user.id
@articles = Article.all
if @article.save
redirect_to articles_path
else
render "index"
end
end
private
# Never trust parameters from the scary internet, only allow the white list through.
def article_params
params.require(:article).permit(:content, attachments_attributes: [:id, :file, :_destroy])
end
class Attachment < ActiveRecord::Base
mount_uploader :file, AttachmentUploader
belongs_to :attachable, polymorphic: true
end
# Never trust parameters from the scary internet, only allow the white list through.
def article_params
params.require(:article).permit(:content, attachments_attributes: [:id, :file, :file_cache, :_destroy])
end
通过提交文章传递Parameters: {"utf8"=>"✓", "authenticity_token"=>"zwVA0Z7q7qj/diHSatDPihKEGY0K2JGTc1aRwVj5RIZQr/OqK/xQRPIXpjIdY1gzuGtYrgYhVU3uujn47cB+Iw==", "article"=>{"content"=>"", "attachments_attributes"=>{"0"=>{"file"=>#<ActionDispatch::Http::UploadedFile:0x007f5dce86e8a8 @tempfile=#<Tempfile:/tmp/RackMultipart20151003-3227-1gsru7x.JPG>, @original_filename="YourPhoto_0001.JPG", @content_type="image/jpeg", @headers="Content-Disposition: form-data; name=\"article[attachments_attributes][0][file]\"; filename=\"YourPhoto_0001.JPG\"\r\nContent-Type: image/jpeg\r\n">, "file_cache"=>"1443854078-3227-6970/YourPhoto_0001.JPG", "id"=>"", "_destroy"=>"false"}}}, "commit"=>"Submit"}