Tips and tricks to use Simple File Upload with Ruby form helpers, permitted parameters, and Devise.
Don't forget to add the javascript snippet as described in the General section!
If you are using Ruby on Rails with a model backed form as below:
<%= form_with model: @user do |form| %>
Add the hidden input field using the form
variable:
<%= form.hidden_field :avatar_url, class: "simple-file-upload" %>
This will automatically create the html element:
<input type="hidden" name="user[avatar_url]" id="user_avatar_url" class="simple-file-upload">
If you are using Ruby on Rails without a model backed form you can use a hidden_field_tag
helper:
<%= hidden_field_tag "avatar_url" class="simple-file-upload" %>
Which becomes the html element:
<input type="hidden" name="avatar_url" id="avatar_url" class="simple-file-upload">
Using the example of adding an avatar to a user, add this url as a string to your users table:
rails generate migration AddAvatarUrlToUsers avatar_url:string
Migrate the database:
rails db:migrate
If you are using Ruby on Rails strong parameters, you must add the new url to the permitted params:
def user_params
params.require(:user).permit(:avatar_url)
end
If you are using Devise as your User model in Ruby on rails, modify your permitted parameters in application_controller.rb
devise_parameter_sanitizer.permit(:account_update, keys: [:name, :avatar_url])
Using the avatar_url
example the existing input
element:
<input type="hidden" name="user[avatar_url]" id="user_avatar_url" class="simple-file-upload">
Will add the URL to the uploaded file as the value
parameter:
<input type="hidden" id="user_avatar_url" name="user[avatar_url]" class="simple-file-upload" value="https://subdomain.app.simplefileupload.com/randomString/filename.extension">
Where "https://subdomain.app.simplefileupload.com/randomString/filename.extension"
is the url of the file the user uploaded. When you submit your form, this value will be available as a normal parmeter.