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"}