public
Created

  • Download Gist
Image upload example
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41
class User < ActiveRecord::Base
has_one :photo, :dependent => :destroy
accepts_nested_attributes_for :photo, :allow_destroy => true
end
 
 
#using paperclip gem for user's images
class Photo < ActiveRecord::Base
belongs_to :user
 
has_attached_file :data, :styles => { :thumb=> "75x75#", :small => "100x100#"}, :whiny => false, :keep_old_files => false
 
validate :validates_account_avatar
 
def validates_account_avatar
allowed_mime_types = ["image/bmp", "image/gif", "image/jpeg", "image/png"]
max_size = 1.megabytes
errors[:format] << "Photo should be bmp, gif, jpeg or png." unless allowed_mime_types.include?(data.content_type.to_s)
errors[:size] << "Photo should be smaller than 1 Mb." if data.size > max_size
return true if self.errors.empty?
return false
end
end
 
#user form
<%= form_for @user, :html => {:multipart => true} do |f| %>
<% if @user.errors.any? %>
<p><%= pluralize(@user.errors.count, "error") %></strong> prohibited this user from being saved:</p>
<ul>
<% @user.errors.full_messages.each do |msg| %>
<li><%= msg %></li>
<% end %>
</ul>
<% end %>
 
<%= f.text_field :name %>
<%= f.fields_for :photo do |photo| %>
<%= photo.file_field :data %>
<% end %>
<%=f.submit "Save changes", :class=>"btn btn-primary", "data-disable-with" => "wait..."%>
<% end %>

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.