ruby on rails - Validate picture upload before create object -


so have car class have many photos. , when creating new car need ensure user did select picture first. here implementation.

class car < activerecord::base  has_many :photos end 

and class photo:

class photo < activerecord::base belongs_to :car  has_attached_file :image, styles: { medium: "300x300>", thumb: "100x100>" } validates_attachment_content_type :image, content_type: /\aimage\/.*\z/ end 

here part of car form:

  <%= form_for @car, :html => { multipart: true } |f| %>              <div class="col-xs-6">                 <div class="form-group">                     <label>modele</label>                     <%= f.text_field :modele, placeholder: "modele", class: "form-control" %>                 </div>             </div>                 <div class="row">                 <div class="col-md-4">                     <div class="form-group">                                                     <span class="btn btn-default btn-file">                             <i class="fa fa-cloud-upload fa-lg"></i> upload photos                              <%= file_field_tag "images[]", type: :file, multiple: true %>                         </span>                     </div>                       </div>             </div>    <% end %> 

take @ https://github.com/carrierwaveuploader/carrierwave/wiki/how-to:-validate-attachment-file-size

require 'file_size_validator'  class photo < activerecord::base   belongs_to :car    validates :image, presence: true end 

this should trick

happy hacking


Comments