0

I have an articles form that lists articles, includes a form to submit a new article with nested fields for attaching photos.

The form works and saves both the article and the photos.

When the validation fails I simply render the index action which displays the validation errors correctly.

When I render the index action the incorrect form data is displayed correctly however the selected photos are not retained so the user has to be correct their data entry and then reattach the photos again.

This is a problem as users tend to correct the form data then submit without noticing their photos have not been attached.

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

attachment.rb

class Attachment < ActiveRecord::Base
  mount_uploader :file, AttachmentUploader
  belongs_to :attachable, polymorphic: true
end

new discussion controller params

# 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

params passed by submitting article

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"}
Dercni
  • 1,216
  • 3
  • 18
  • 38
  • 1
    check this it might help you http://stackoverflow.com/questions/15680484/how-to-persist-file-upload-fields-after-a-rails-validation-error – Arvind Oct 03 '15 at 04:35
  • 1
    https://github.com/carrierwaveuploader/carrierwave#making-uploads-work-across-form-redisplays Perfect. This is exactly what I am after however it's not working. The value of file_cache is bank. – Dercni Oct 03 '15 at 06:24
  • I stand corrected. The value of file_cache cache is not blank however the attachment is not persisted over a form redisplay as required. – Dercni Oct 03 '15 at 06:37

0 Answers0