Reputation: 8293
I am using the simple_form (https://github.com/plataformatec/simple_form) library to do a file upload using Rails 4.2.5. I want to disallow file uploads unless a file is present in the form using simple_form but do not know exactly how to do this. My code is below:
<%= simple_form_for @business, html: { multipart: true } do |f| %>
<%= f.simple_fields_for :attached_files, AttachedFile.new do |af| %>
<%= af.input :file, as: :file, label: false %>
<% end %>
<%= f.button :submit,
'Upload File',
class: 'btn btn-mini btn-success hidden',
id: 'submit-file-upload' %>
<% end %>
Upvotes: 3
Views: 6975
Reputation: 2267
Let me know if you're looking for something a little more verbose, but the simplest implementation of this is simply by adding a required field to the input statement:
<%= simple_form_for @business, html: { multipart: true } do |f| %>
<%= f.simple_fields_for :attached_files, AttachedFile.new do |af| %>
<%= af.input :file, as: :file, label: false, required: true %>
<% end %>
<%= f.button :submit,
'Upload File',
class: 'btn btn-mini btn-success hidden',
id: 'submit-file-upload' %>
<% end %>
Additionally, you're going to want to make sure you're doing server-side validations, as they're really the only concrete validations (browser validations can always be tampered with)
def create
@business = Business.new(business_params)
unless params[:file].nil?
if @business.save!
redirect_to root_path
else
render :new
end
end
Lastly, make sure your config file is set to handle browser validations:
SimpleForm.browser_validations = true
Upvotes: 9