Skip to content

Instantly share code, notes, and snippets.

@karmiclychee
Last active December 16, 2015 11:59
Show Gist options
  • Save karmiclychee/5431542 to your computer and use it in GitHub Desktop.
Save karmiclychee/5431542 to your computer and use it in GitHub Desktop.
class Profile < ActiveRecord::Base
belongs_to :user
has_many :collections
attr_accessible :avatar, :name, :title, :description
validates :name, presence: true, length: { minimum: 1, maximum: 60 }
validates :description, presence: true, length: { minimum: 1, maximum: 60 }
validates :title, presence: true, length: { minimum: 1, maximum: 60 }
has_attached_file :avatar, :styles => { :medium => "300x300#", :thumb => "100x100#" }, :default_url => "/assets/generic.png"
before_save :default_values
private
def default_values
name ||= "Tell us your name!"
title ||= "What do you do?"
description ||= "Tell us about yourself!"
end
end
[10] pry(main)> a.save
(0.2ms) begin transaction
User Exists (0.3ms) SELECT 1 AS one FROM "users" WHERE "users"."email" = 'a@a.com' LIMIT 1
User Exists (0.1ms) SELECT 1 AS one FROM "users" WHERE "users"."username" = 'username' LIMIT 1
(0.0ms) rollback transaction
=> false
[11] pry(main)> a.errors
=> #<ActiveModel::Errors:0x0000000726fed8
@base=
#<User id: nil, email: "a@a.com", encrypted_password: "$2a$10$ntsSfoqVtaMX24sIdS488OI4ZM.uJZFlx.j6Xy8y4zFo...", reset_password_token: nil, reset_password_sent_at: nil, remember_created_at: nil, sign_in_count: 0, current_sign_in_at: nil, last_sign_in_at: nil, current_sign_in_ip: nil, last_sign_in_ip: nil, created_at: nil, updated_at: nil, username: "username", confirmation_token: nil, confirmed_at: nil, confirmation_sent_at: nil, unconfirmed_email: nil>,
@messages=
{:"profile.name"=>
["can't be blank", "is too short (minimum is 1 characters)"],
:"profile.description"=>
["can't be blank", "is too short (minimum is 1 characters)"],
:"profile.title"=>
["can't be blank", "is too short (minimum is 1 characters)"]}>
class User < ActiveRecord::Base
# Include default devise modules. Others available are:
# :token_authenticatable, :confirmable,
# :lockable, :timeoutable and :omniauthable
devise :database_authenticatable, :registerable, :confirmable,
:recoverable, :rememberable, :trackable, :validatable
# Setup accessible (or protected) attributes for your model
attr_accessible :email, :password, :password_confirmation, :remember_me,
:username, :profiles
attr_accessor :name
has_one :profile
accepts_nested_attributes_for :profile
validates :username, uniqueness: true, presence: true, length: { minimum: 1, maximum: 1000 }
before_validation :set_profile
private
def set_profile
unless self.profile
build_profile
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment