CodeNewbie Community 🌱

Mike Rogers
Mike Rogers

Posted on

Upload Files with Simple File Upload

Uploading files to the cloud isn't the easiest. In the past I've used AWS S3 (which is really good) but configuring my API keys to have the correct access & setting up mirrors into another provider is tricky.

I quite like that Simple File Upload allowed me to get setup within a few minutes & also the founder has a fantastic podcast.

The Code

The full source code can be found on GitHub.

First I updated the layout to include the JavaScript snippet.

<!-- app/views/layouts/application.html.erb -->
<script src=""></script>
Enter fullscreen mode Exit fullscreen mode

Then I wrote a migration to add the field image_url to my posts model.

# db/migrate/20210125143751_add_image_url_to_posts.rb
class AddImageUrlToPosts < ActiveRecord::Migration[6.1]
  def change
    add_column :posts, :image_url, :string
Enter fullscreen mode Exit fullscreen mode

Then I updated the posts form to include the image_url field. For the upload field I added the simple-file-upload class.

<!-- app/views/posts/_form.html.erb -->
  <div class="field">
    <%= form.label :image_url %><br />
    <%= form.text_field :image_url, class: 'simple-file-upload' %>
Enter fullscreen mode Exit fullscreen mode
# app/controllers/posts_controller.rb
class PostsController < ApplicationController
  # [..]


    # Only allow a list of trusted parameters through.
    def post_params
      # I added image_url to the permitted params
      params.require(:post).permit(:title, :body, :image_url)
Enter fullscreen mode Exit fullscreen mode

Top comments (0)