Skip to content

Instantly share code, notes, and snippets.

@turizoft
Created May 22, 2015 23:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save turizoft/eb51292490722182d363 to your computer and use it in GitHub Desktop.
Save turizoft/eb51292490722182d363 to your computer and use it in GitHub Desktop.
Business card model definition
class Card < ActiveRecord::Base
# Searchable
searchkick callbacks: :async, text_middle: [:name]
def search_data
as_json only: [:name, :description]
end
# Asociations
has_many :card_social_networks
has_many :social_networks, through: :card_social_networks
has_many :locations
has_many :emails
has_many :card_users
has_many :users, through: :card_users
# Validations
validates :name, length: { in: 1..32 }
validates :description, length: { in: 1..100 }
# Callbacks
before_create :generate_handshake_token
before_validation :format_attributes
# Nested attributes
accepts_nested_attributes_for :card_social_networks, :emails, :locations, allow_destroy: true
private
def format_attributes
self.name = name.strip.squeeze(' ') if name?
self.escaped_name = Formatter.escape_string(name) if name?
end
def generate_handshake_token
begin
self.handshake_token = SecureRandom.hex(32)
end while self.class.exists?(handshake_token: handshake_token)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment