0
votes

I am attempting to create a simple file sharing application using Ruby on Rails. The following is my controller:

  1 class AttachmentsController < ApplicationController
  2   def new
  3   end
  4
  5   def create
  6     @attachment = Attachment.new(attachment_params)
  7     @attachment.save
  8     redirect_to @attachment
  9   end
 10
 11   def show
 12     @attachment = Attachment.find(params[:attachment]['file'].original_filename)
 13   end
 14
 15   private
 16   def attachment_params
 17     params.require()
 18   end
 19 end

The file I upload contains params in the following format:

{ "utf8" => "✓", "authenticity_token" => "EPd9Ed7C/qBsKu4R+t3q1Xm8aYSH7M6ZcvbpjHiJ9BnZlX0ldVCIc5AP1zcKaUB4Y7MzY8aLJI+gcPekE/hn6Q==", "attachment" => { "file" => # < ActionDispatch::Http::UploadedFile: 0x007f8612bab4f0@ tempfile = # < Tempfile: /var/folders / ft / 6 m5lh5sd2bb3dwj8pczwdjtm0000gn / T / RackMultipart20150622 - 5173 - 1 dfsg86.jpg > , @original_filename = "Kesari_bhath.jpg", @content_type = "image/jpeg", @headers = "Content-Disposition: form-data; name=\"attachment[file]\"; filename=\"Kesari_bhath.jpg\"\r\nContent-Type: image/jpeg\r\n" > }, "commit" => "Save Attachment" }

So I can access the @original_filname as params[:attachment]['file'].original_filename

How do write this nested attribute in the params.require (line 17)?

Note that the hash is 'file' and not file (mind the quotes). I cannot access it with permit.require(:attachment).permit(:file) or permit.require(:attachment).permit('file') both of which cause unknown attribute 'file' for Attachment error.

3

3 Answers

1
votes

Simply you can try this:

def attachment_params
  params.require(:attachment).permit(:file)
end
0
votes

params.require(:attachment).permit(params['file'])

Allowed me to obtain values in the hash with file as key.

0
votes

You can try something like this:

params.require(:attachment).permit(... , :file_attributes: [:original_filename])