1

I'm trying to make a file_field required before the form is able to be submitted, using Rails and ERB, and I'm drawing a blank.

<%= form_for Image.new, html: {multipart: true} do |i| %>
  <%= i.label :description %>
  <%= i.text_field :description %>
  <%= i.file_field :image %>  <------**** This Line ****
  <%= i.submit "Upload" %>
<% end %>

I've tried using 'required' in various ways and searched the web but to no avail. Is this something that I should seek to validate in the model instead?

My model is this:

class Image < ActiveRecord::Base
  has_many :comments, dependent: :destroy
  has_many :likes, dependent: :destroy
  belongs_to :user

  has_attached_file :image, :styles => { :large => "600x600>", :medium => "300x300>", :thumb => "100x100>" }, :default_url => "/images/:style/missing.png"
  validates_attachment_content_type :image, :content_type => /\Aimage\/.*\Z/
end
sanjsanj
  • 1,003
  • 9
  • 20

1 Answers1

4

At the bottom of the list of suggested answers I found what I was looking for in this stack thread

validates :image, :presence => true

I simply had to add that to my model and it doesn't let the form submit without an image attachment.

Community
  • 1
  • 1
sanjsanj
  • 1,003
  • 9
  • 20
  • 1
    Or with html `<%= i.file_field :image, required: true %>` – Vlad Hilko May 22 '20 at 17:38
  • It's ideal to validate on both levels. HTML as per: @EvanRoss, and the model as sanjsanj. If you want to be even thorough, you can have a check on the controller function handling that submit request. – Talita Sep 13 '21 at 06:47
  • Both in the model and in the HTML is ideal so the User doesn't have to submit the form before they see it's required. – Joshua Pinter Aug 21 '23 at 20:05