Created
May 22, 2015 23:12
-
-
Save turizoft/eb51292490722182d363 to your computer and use it in GitHub Desktop.
Business card model definition
This file contains hidden or 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 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