Tyler Tyler - 3 months ago 13
Ruby Question

Rails ActiveRecord Create with file params

In my app's

seeds.rb
I create a Template object used for testing purposes. Normally a Template is created through a form that requires a file uploaded with it. The file gets stored in S3 and the url gets added to the Template object as an attribute.

How can I pass in the file body and file name in my seeds file so the url gets correctly set on the Template object?

seeds.rb

# need to include params[:template][:body].tempfile
# and params[:template][:body].original_filename
template = user.templates.new(name: 'test_template.docx')
template.save


templates_controller.rb

def create
# upload to s3
file_name = params[:template][:body].original_filename
s3 = Amazon::S3.resource
obj = s3.bucket(User.directory_bucket).object(current_user.uuid + '/templates/' + file_name)

obj.upload_file(params[:template][:body].tempfile)

# create template
@template = Template.create(name: file_name, url: obj.public_url, user_id: params[:template][:user_id])

# redirects/response
end

Answer

Give this a try.

user = ... # lookup the user you want to associate with

file_name = 'test_template.docx'
s3        = Amazon::S3.resource
obj       = s3.bucket(User.directory_bucket).object(user.uuid + '/templates/' + file_name)

obj.upload_file(File.new('path/to/' + file_name))

template = user.templates.new(name: file_name)
template.save
Comments