https://github.com/thoughtbot/paperclip
Paperclip is a gem used for attaching to Rails applications.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class UserPhoto < ActiveRecord::Base | |
belongs_to :user | |
has_attached_file :photo, :styles => | |
{ :medium => "300>x300", :thumb => "200x200#" }, | |
:default_url => "assets/images/:style/missing.png" | |
validates :user_id, presence: true | |
validates :caption, length: { maximum: 140 } | |
validates :photo_width, presence: true | |
validates :photo_height, presence: true | |
# Validations for Photo's | |
validates :photo, presence: true | |
# Don't let people upload Giant phot's and charge alot of out AWS account | |
validates_attachment_size :photo, :less_than => 5.megabytes | |
# Only let people uplad a photo | |
validates_attachment_content_type :photo, | |
:content_type => ['image/jpeg', 'image/png', 'image/jpg'] | |
after_post_process :save_image_dimensions | |
def save_image_dimensions | |
geo = Paperclip::Geometry.from_file(photo.queued_for_write[:original]) | |
self.photo_width = geo.width.to_i | |
self.photo_height = geo.height.to_i | |
end | |
end |
<%= image_tag @user.user_photo.url %>
<%= image_tag @user.user_photo.url(:medium) %>
<%= image_tag @user.user_photo.url(:thumb) %>
Important Finds
:thumb => "200x200#"
The # signifies that this image is going to be saved as as a square on the inside of the photo. This is very useful for user profile pictures.
:medium => "300>x300"
This ensures that the image will have a a width greater than 300 px.
Profile Pictures
User has_many UserPhotos
- I started by saving a bolean field on the UserPhoto to check if there is a default photo.
- I later found out that it is better to save a link on the user model
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class AddDefaultPhotoIdToUsers < ActiveRecord::Migration | |
def change | |
add_column :users, :default_photo_id, :integer | |
remove_column :user_photos, :default_photo | |
end | |
end |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def get_default_photo | |
self.user_photos.find_by_id(default_photo_id) | |
end |
How to Link to AWS Account
- It is a a bad idea to save images to the project. Amazon Web Server and Heroku work well together in order to save files at a cheap fast cost.
No comments:
Post a Comment